UIPicker detect tap on currently selected row

Viewed 18209

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?

8 Answers

Nikolay's answer in Swift 4:

First, add a UITapGestureRecognizer to your UIPickerView in viewDidLoad() and let your UIViewController conform to the 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:

@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:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}
  1. Add a tapGestureRecognizer to the pickerView as already suggested

  2. Provide views for the picker rows, not the title, via

    -(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

  3. In the gesture's callback method do this

-(void)pickerTapped:(UIGestureRecognizer *)gestureRecognizer {

UIPickerView * pv = (id)gestureRecognizer.view;
UIView * selView = [pv viewForRow:[pv selectedRowInComponent:0]
                     forComponent:0];
CGPoint touchPoint = [gestureRecognizer locationInView:selView];
BOOL tapOnSelection = CGRectContainsPoint(selView.bounds, touchPoint);

if (tapOnSelection) ...

}

I think is more elegant then doing pixel math

Related