点击选定的行时,关闭UIPickerView

时间:2012-08-26 15:37:33

标签: iphone objective-c ios uipickerview

我正在使用UIPickerView让用户从几个选项中选择,当我显示选择器时,我滚动到最后选择的行。

当用户选择一行时我想总是关闭选择器(即使用户点击已选择的行),我也会在didSelectRow方法中关闭选择器。

问题是,如果用户重新选择所选行,则didSelectRow方法不会被调用,因此我无法关闭选择器..

1 个答案:

答案 0 :(得分:2)

一种解决方案是创建UIPickerView的子类并覆盖touchesEnded:withEvent:方法:

- (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];
    }
}

或者您可以向UIPickerView添加UITapGestureRecognizer

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

然后:

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

虽然这不会影响UIPickerView处理水龙头的方式,但我并非百分百肯定。