Search code examples
iosuipickerview

iOS UIPickerView: How to limit the scrolling range


When you scroll UIPickerView you can move your finger on the touchpad up and down - far up and down to how big the screen is. Is there a way to limit this range of scrolling up and down to the area of the UIPickerView? So that once you move your finger outside of the UIPickerView the scrolling of the UIPickerView stops? I am making UIPIckerView as a spinner in a game, and I need to achieve this for a fair gaming.


Solution

  • //viewDidLoad

    UILongPressGestureRecognizer* gestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pickerLongPressDetected:)];
        gestureRecognizer.minimumPressDuration = .001;
        gestureRecognizer.cancelsTouchesInView = NO;
        gestureRecognizer.delegate = self;
        [self.rollerView addGestureRecognizer:gestureRecognizer];
    
    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
        // return
        return true;
    }
    
    -(void)pickerLongPressDetected:(UILongPressGestureRecognizer *)gesture
    {
        CGPoint touchPoint = [gesture locationInView:self.view];
    
        CGRect frame = self.rollerView.frame;
    
        if(!CGRectContainsPoint(frame, touchPoint))
        {
            //methods for when you scroll outside of your picker view's frame
        }
    }