UIPicker detect tap on currently selected row

时间:2021-12-24 15:04:11

I have a UIPickerView and The method didSelectRow is not called when tapping on a selected row. I need to handle this case. Any ideas?

我有一个UIPickerView,并且在点击选定的行时不会调用didSelectRow方法。我需要处理这个案子。有任何想法吗?

7 个解决方案

#1


22  

First, conform the class to the UIGestureRecognizerDelegate protocol

首先,使类符合UIGestureRecognizerDelegate协议

Then, in the view setup:

然后,在视图设置中:

UITapGestureRecognizer *tapToSelect = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                                 action:@selector(tappedToSelectRow:)];
tapToSelect.delegate = self;
[self.pickerView addGestureRecognizer:tapToSelect];

And elsewhere:

#pragma mark - Actions

- (IBAction)tappedToSelectRow:(UITapGestureRecognizer *)tapRecognizer
{
    if (tapRecognizer.state == UIGestureRecognizerStateEnded) {
        CGFloat rowHeight = [self.pickerView rowSizeForComponent:0].height;
        CGRect selectedRowFrame = CGRectInset(self.pickerView.bounds, 0.0, (CGRectGetHeight(self.pickerView.frame) - rowHeight) / 2.0 );
        BOOL userTappedOnSelectedRow = (CGRectContainsPoint(selectedRowFrame, [tapRecognizer locationInView:self.pickerView]));
        if (userTappedOnSelectedRow) {
            NSInteger selectedRow = [self.pickerView selectedRowInComponent:0];
            [self pickerView:self.pickerView didSelectRow:selectedRow inComponent:0];
        }
    }
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return true;
}

#2


9  

Nikolay's Answer with Swift:

尼古拉对斯威夫特的回答:

let tap = UITapGestureRecognizer(target: self, action: #selector(OCAccountSettingsViewController.pickerTapped(_:)))
tap.cancelsTouchesInView = false
tap.delegate = self
pickerView.addGestureRecognizer(tap)

important let your viewController confirm the UIGestureRecognizerDelegate otherwise handler won't fire:

重要的是让你的viewController确认UIGestureRecognizerDelegate,否则处理程序将不会触发:

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true}

the last step will be the handler for tap event:

最后一步将是tap事件的处理程序:

func pickerTapped(tapRecognizer:UITapGestureRecognizer)
{
    if (tapRecognizer.state == UIGestureRecognizerState.Ended)
    {
      let rowHeight : CGFloat  = self.pickerView.rowSizeForComponent(0).height
      let selectedRowFrame: CGRect = CGRectInset(self.pickerView.bounds, 0.0, (CGRectGetHeight(self.pickerView.frame) - rowHeight) / 2.0 )
      let userTappedOnSelectedRow = (CGRectContainsPoint(selectedRowFrame, tapRecognizer.locationInView(pickerView)))
      if (userTappedOnSelectedRow)
      {
        let selectedRow = self.pickerView.selectedRowInComponent(0)
        //do whatever you want here
      }
    }
  }

#3


6  

Nikolay's answer in Swift 4:

尼古拉在Swift 4中的回答:

First, add a UITapGestureRecognizer to your UIPickerView in viewDidLoad() and let your UIViewController conform to the UIGestureRecognizerDelegate.

首先,在viewDidLoad()中向UIPickerView添加一个UITapGestureRecognizer,让你的UIViewController符合UIGestureRecognizerDelegate。

let tap = UITapGestureRecognizer(target: self, action: #selector(pickerTapped))
tap.delegate = self
self.pickerView.addGestureRecognizer(tap)

Add this function which calls your UIPickerViewDelegate when a tap on a row has been detected:

添加此函数,在检测到某行时调用UIPickerViewDelegate:

@objc func pickerTapped(tapRecognizer: UITapGestureRecognizer) {
    if tapRecognizer.state == .ended {
        let rowHeight = self.pickerView.rowSize(forComponent: 0).height
        let selectedRowFrame = self.pickerView.bounds.insetBy(dx: 0, dy: (self.pickerView.frame.height - rowHeight) / 2)
        let userTappedOnSelectedRow = selectedRowFrame.contains(tapRecognizer.location(in: self.pickerView))
        if userTappedOnSelectedRow {
            let selectedRow = self.pickerView.selectedRow(inComponent: 0)
            pickerView(self.pickerView, didSelectRow: selectedRow, inComponent: 0)
        }
    }
}

Add the shouldRecognizeSimultaneouslyWith method from UIGestureRecognizerDelegate:

从UIGestureRecognizerDelegate添加shouldRecognizeSimultaneouslyWith方法:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

#4


5  

Solution touchesBegan: / touchesEnded: worked fine for me when using iOS 4.2/4.3, but they stopped working with iOS. Finally I got this solution which may be helpful: using tap gesture recognition.

解决方案touchesBegan:/ touchesEnded:在使用iOS 4.2 / 4.3时对我来说很好,但他们停止使用iOS。最后,我得到了这个可能有用的解决方案:使用轻敲手势识别。

    IBOutlet UIPickerView *picker;

    [picker addGestureRecognizer:
        [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerTapped:)] autorelease]
    ];

In this case when a user taps on picker view, the selector

在这种情况下,当用户点击选择器视图时,选择器

    -(void)pickerTapped:(UIGestureRecognizer *)gestureRecognizer

is invoked. Worked for me on both iOS 4.2+ / 5.0

被调用。在iOS 4.2+ / 5.0上为我工作

#5


0  

I solved this by subclassing a common superview and intercepting the touch events before sending them forward. In interface builder, I also added a button where the selector area is, attached an action to the touch up event, and sent the button to "the back" (that's very important so it doesn't return itself in hitTest). The most relevant code is below. It could be improved for more complicated, like multitouch, cases.

我通过继承一个共同的超级视图并在发送它们之前拦截触摸事件来解决这个问题。在界面构建器中,我还添加了一个选项区域的按钮,附加了一个动作到触摸事件,并将按钮发送到“后面”(这非常重要,因此它不会在hitTest中返回)。最相关的代码如下。对于更复杂的情况,例如多点触控,可以改进它。

    @implementation InterceptorView


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
 UITouch *t=[touches anyObject];
 CGPoint p=[t locationInView:button];
 if ([button hitTest:p withEvent:event]) 
  started_in_button=YES;
 [hitView touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
 [hitView touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
 UITouch *t=[touches anyObject];
 CGPoint p=[t locationInView:button];
 if ([button hitTest:p withEvent:event] && started_in_button) {
  started_in_button=NO;
  [button sendActionsForControlEvents:UIControlEventTouchUpInside];
 }
 [hitView touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
 [hitView touchesCancelled:touches withEvent:event];
}

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
 hitView = [super hitTest:point withEvent:event];
 return self;
}

#6


0  

Here's swift code for figuring out if user tapped inside the selected row or not. I just converted obj-c code from Nikolay's answer.

这是用于确定用户是否在所选行内轻敲的快速代码。我刚从Nikolay的回答中转换了obj-c代码。

func pickerTapped(sender: UITapGestureRecognizer){
    let rowHeight = self.rowSizeForComponent(0).height
    let selectedRowFrame = CGRectInset(self.bounds, 0.0, (CGRectGetHeight(self.frame) - rowHeight) / 2.0)
    let userTappedOnSelectedRow = CGRectContainsPoint(selectedRowFrame, sender.locationInView(self))
    if( userTappedOnSelectedRow ){
        // .. your action here ..
    }
}

#7


0  

Here's Nikolay's trick in Swift v3:

这是Nikolay在Swift v3中的诀窍:

First, make your UIViewController implement protocol UIGestureRecognizerDelegate, and add this method to it:

首先,使您的UIViewController实现协议UIGestureRecognizerDelegate,并将此方法添加到它:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

Then, apply a UITapGestureRecognizer on the picker, and when your target is called, call the following extension method:

然后,在选择器上应用UITapGestureRecognizer,并在调用目标时调用以下扩展方法:

extension UIPickerView {
    func pickerTapped(nizer: UITapGestureRecognizer, onPick: @escaping (Int) -> ()) {
        if nizer.state == .ended {
            let rowHeight = self.rowSize(forComponent: 0).height
            let selectedRowFrame = self.bounds.insetBy(dx: 0, dy: (self.frame.height - rowHeight) / 2)

            // check if begin and end tap locations both fall into the row frame:
            if selectedRowFrame.contains(nizer.location(in: self)) &&
                   selectedRowFrame.contains(nizer.location(ofTouch: 0, in: self)) {
                onPick(self.selectedRow(inComponent: 0))
            }
        }
    }
}

#1


22  

First, conform the class to the UIGestureRecognizerDelegate protocol

首先,使类符合UIGestureRecognizerDelegate协议

Then, in the view setup:

然后,在视图设置中:

UITapGestureRecognizer *tapToSelect = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                                 action:@selector(tappedToSelectRow:)];
tapToSelect.delegate = self;
[self.pickerView addGestureRecognizer:tapToSelect];

And elsewhere:

#pragma mark - Actions

- (IBAction)tappedToSelectRow:(UITapGestureRecognizer *)tapRecognizer
{
    if (tapRecognizer.state == UIGestureRecognizerStateEnded) {
        CGFloat rowHeight = [self.pickerView rowSizeForComponent:0].height;
        CGRect selectedRowFrame = CGRectInset(self.pickerView.bounds, 0.0, (CGRectGetHeight(self.pickerView.frame) - rowHeight) / 2.0 );
        BOOL userTappedOnSelectedRow = (CGRectContainsPoint(selectedRowFrame, [tapRecognizer locationInView:self.pickerView]));
        if (userTappedOnSelectedRow) {
            NSInteger selectedRow = [self.pickerView selectedRowInComponent:0];
            [self pickerView:self.pickerView didSelectRow:selectedRow inComponent:0];
        }
    }
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return true;
}

#2


9  

Nikolay's Answer with Swift:

尼古拉对斯威夫特的回答:

let tap = UITapGestureRecognizer(target: self, action: #selector(OCAccountSettingsViewController.pickerTapped(_:)))
tap.cancelsTouchesInView = false
tap.delegate = self
pickerView.addGestureRecognizer(tap)

important let your viewController confirm the UIGestureRecognizerDelegate otherwise handler won't fire:

重要的是让你的viewController确认UIGestureRecognizerDelegate,否则处理程序将不会触发:

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true}

the last step will be the handler for tap event:

最后一步将是tap事件的处理程序:

func pickerTapped(tapRecognizer:UITapGestureRecognizer)
{
    if (tapRecognizer.state == UIGestureRecognizerState.Ended)
    {
      let rowHeight : CGFloat  = self.pickerView.rowSizeForComponent(0).height
      let selectedRowFrame: CGRect = CGRectInset(self.pickerView.bounds, 0.0, (CGRectGetHeight(self.pickerView.frame) - rowHeight) / 2.0 )
      let userTappedOnSelectedRow = (CGRectContainsPoint(selectedRowFrame, tapRecognizer.locationInView(pickerView)))
      if (userTappedOnSelectedRow)
      {
        let selectedRow = self.pickerView.selectedRowInComponent(0)
        //do whatever you want here
      }
    }
  }

#3


6  

Nikolay's answer in Swift 4:

尼古拉在Swift 4中的回答:

First, add a UITapGestureRecognizer to your UIPickerView in viewDidLoad() and let your UIViewController conform to the UIGestureRecognizerDelegate.

首先,在viewDidLoad()中向UIPickerView添加一个UITapGestureRecognizer,让你的UIViewController符合UIGestureRecognizerDelegate。

let tap = UITapGestureRecognizer(target: self, action: #selector(pickerTapped))
tap.delegate = self
self.pickerView.addGestureRecognizer(tap)

Add this function which calls your UIPickerViewDelegate when a tap on a row has been detected:

添加此函数,在检测到某行时调用UIPickerViewDelegate:

@objc func pickerTapped(tapRecognizer: UITapGestureRecognizer) {
    if tapRecognizer.state == .ended {
        let rowHeight = self.pickerView.rowSize(forComponent: 0).height
        let selectedRowFrame = self.pickerView.bounds.insetBy(dx: 0, dy: (self.pickerView.frame.height - rowHeight) / 2)
        let userTappedOnSelectedRow = selectedRowFrame.contains(tapRecognizer.location(in: self.pickerView))
        if userTappedOnSelectedRow {
            let selectedRow = self.pickerView.selectedRow(inComponent: 0)
            pickerView(self.pickerView, didSelectRow: selectedRow, inComponent: 0)
        }
    }
}

Add the shouldRecognizeSimultaneouslyWith method from UIGestureRecognizerDelegate:

从UIGestureRecognizerDelegate添加shouldRecognizeSimultaneouslyWith方法:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

#4


5  

Solution touchesBegan: / touchesEnded: worked fine for me when using iOS 4.2/4.3, but they stopped working with iOS. Finally I got this solution which may be helpful: using tap gesture recognition.

解决方案touchesBegan:/ touchesEnded:在使用iOS 4.2 / 4.3时对我来说很好,但他们停止使用iOS。最后,我得到了这个可能有用的解决方案:使用轻敲手势识别。

    IBOutlet UIPickerView *picker;

    [picker addGestureRecognizer:
        [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerTapped:)] autorelease]
    ];

In this case when a user taps on picker view, the selector

在这种情况下,当用户点击选择器视图时,选择器

    -(void)pickerTapped:(UIGestureRecognizer *)gestureRecognizer

is invoked. Worked for me on both iOS 4.2+ / 5.0

被调用。在iOS 4.2+ / 5.0上为我工作

#5


0  

I solved this by subclassing a common superview and intercepting the touch events before sending them forward. In interface builder, I also added a button where the selector area is, attached an action to the touch up event, and sent the button to "the back" (that's very important so it doesn't return itself in hitTest). The most relevant code is below. It could be improved for more complicated, like multitouch, cases.

我通过继承一个共同的超级视图并在发送它们之前拦截触摸事件来解决这个问题。在界面构建器中,我还添加了一个选项区域的按钮,附加了一个动作到触摸事件,并将按钮发送到“后面”(这非常重要,因此它不会在hitTest中返回)。最相关的代码如下。对于更复杂的情况,例如多点触控,可以改进它。

    @implementation InterceptorView


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
 UITouch *t=[touches anyObject];
 CGPoint p=[t locationInView:button];
 if ([button hitTest:p withEvent:event]) 
  started_in_button=YES;
 [hitView touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
 [hitView touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
 UITouch *t=[touches anyObject];
 CGPoint p=[t locationInView:button];
 if ([button hitTest:p withEvent:event] && started_in_button) {
  started_in_button=NO;
  [button sendActionsForControlEvents:UIControlEventTouchUpInside];
 }
 [hitView touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
 [hitView touchesCancelled:touches withEvent:event];
}

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
 hitView = [super hitTest:point withEvent:event];
 return self;
}

#6


0  

Here's swift code for figuring out if user tapped inside the selected row or not. I just converted obj-c code from Nikolay's answer.

这是用于确定用户是否在所选行内轻敲的快速代码。我刚从Nikolay的回答中转换了obj-c代码。

func pickerTapped(sender: UITapGestureRecognizer){
    let rowHeight = self.rowSizeForComponent(0).height
    let selectedRowFrame = CGRectInset(self.bounds, 0.0, (CGRectGetHeight(self.frame) - rowHeight) / 2.0)
    let userTappedOnSelectedRow = CGRectContainsPoint(selectedRowFrame, sender.locationInView(self))
    if( userTappedOnSelectedRow ){
        // .. your action here ..
    }
}

#7


0  

Here's Nikolay's trick in Swift v3:

这是Nikolay在Swift v3中的诀窍:

First, make your UIViewController implement protocol UIGestureRecognizerDelegate, and add this method to it:

首先,使您的UIViewController实现协议UIGestureRecognizerDelegate,并将此方法添加到它:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

Then, apply a UITapGestureRecognizer on the picker, and when your target is called, call the following extension method:

然后,在选择器上应用UITapGestureRecognizer,并在调用目标时调用以下扩展方法:

extension UIPickerView {
    func pickerTapped(nizer: UITapGestureRecognizer, onPick: @escaping (Int) -> ()) {
        if nizer.state == .ended {
            let rowHeight = self.rowSize(forComponent: 0).height
            let selectedRowFrame = self.bounds.insetBy(dx: 0, dy: (self.frame.height - rowHeight) / 2)

            // check if begin and end tap locations both fall into the row frame:
            if selectedRowFrame.contains(nizer.location(in: self)) &&
                   selectedRowFrame.contains(nizer.location(ofTouch: 0, in: self)) {
                onPick(self.selectedRow(inComponent: 0))
            }
        }
    }
}