Tap Gesture Recognizer正在禁止UITableViewController上的触摸事件

时间:2017-11-23 21:58:15

标签: ios xcode swift3 uigesturerecognizer swift4

我已在TapGuestureRecognizer内设置ViewDidLoad()以解除键盘问题。我的实现如下

class AddRegistrationTableViewController: UITableViewController, UITextFieldDelegate, SelectRoomTableViewControllerDelegate { 
    ...
    override func viewDidLoad() {
    super.viewDidLoad()
    emailAddressTextField.delegate = self
    ...
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:     #selector(dismissKeyboard))
    tableView.addGestureRecognizer(tapGestureRecognizer)
}
...
@objc func dismissKeyboard() {
    emailAddressTextField.endEditing(true)
}

到目前为止,这很好,这可以解雇文本字段。

但是在Table View Controller中,我还有一个segue链接到一个单元格 - 它没有注册tap(因为手势识别器)跟随segue。我需要使用2个手指轻敲单元格以执行segue。我已尝试在代码中删除上面的addGestureRecognizer实现,并按照预期执行segue。

因此,这让我相信手势识别器正在禁止触摸事件进行注册。我可以实现的任何变通方法或解决方案吗?

2 个答案:

答案 0 :(得分:0)

如果你想解雇键盘,为什么你不使用UITableViewDelegate方法而不是UITapGestureRecognizer

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      emailAddressTextField.endEditing(true)
}

还有一件事,表视图是获取轻击手势而不是单元格,这就是为什么不调用segue。

答案 1 :(得分:0)

一个很好的解决方案是实现UIGestureRecognizerDelegate:

class AddRegistrationTableViewController: UITableViewController, UIGestureRecognizerDelegate, UITextFieldDelegate, SelectRoomTableViewControllerDelegate { 
    ...
    override func viewDidLoad() {
    super.viewDidLoad()
    emailAddressTextField.delegate = self
    ...
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    tapGestureRecognizer.delegate = self // You set the UIGestureRecognizerDelegate here
    tableView.addGestureRecognizer(tapGestureRecognizer)
}
...
@objc func dismissKeyboard() {
    emailAddressTextField.endEditing(true)
}

// In this UIGestureRecognizerDelegate's method we will check if the text field is actually being edited 
// and if it's not the case, we will cancel this touch for the gesture
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    return emailAddressTextField.isEditing
}