UIPicker detect tap on currently selected row

后端 未结 8 1415
礼貌的吻别
礼貌的吻别 2020-12-01 10:11

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

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 10:50

    Here's Nikolay's trick in Swift v3:

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

    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:

    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))
                }
            }
        }
    }
    

提交回复
热议问题