1

I'm using UIPickerView to let the user pick from few options, when I show the picker I scroll to the last selected row.

When user select a row I want to always dismiss the picker (even if user tap the already selected row), I dismiss the picker in the didSelectRow method.

The problem is, if the user reselect the selected row the didSelectRow method doesn't get called so I can't dismiss the picker..

user1590031
  • 308
  • 1
  • 5
  • 15

1 Answers1

2

One solution would be to create a subclass of UIPickerView and override the touchesEnded:withEvent: method:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    // dismiss the picker view here, either directly, or you could notifiy
    // the delegate with a custom message:
    if ([self.delegate respondsToSelector:@selector(pickerViewShouldDismiss:)]) {
        [self.delegate pickerViewShouldDismiss:self];
    }
}

Or you could add a UITapGestureRecognizer to the UIPickerView:

UITapGestureRecognizer *tapGR = [UITapGestureRecognizer alloc] initWithTarget:self
                                 action:@selector(pickerViewTapped];
[pickerView addGestureRecognizer:tapGR];

And then:

- (void)pickerViewTapped {
    // dismiss the picker.
}

I'm not 100% sure though this won't interfere with the way UIPickerView handles taps.

DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • No easy solution without subclassing? – user1590031 Aug 26 '12 at 15:47
  • Tap gesture won't work because there is already a tap gesture built inside the pickerView. You will have to play around with the UIGestureRecognizerDelegate methods to separate the two and respond to the custom tap gesture differently. – Stephen Paul Jan 22 '16 at 01:38