无法使用 tapGestureRecognizer 在屏幕上注册点击

Not able to register a tap on the screen using tapGestureRecognizer

我正在尝试使用 Firebase 构建一个聊天应用程序。我正在尝试实现点击手势,以便在键盘打开时关闭键盘。不幸的是,当您点击屏幕时没有任何反应。我尝试了不同的东西,结果相同。如果有人知道它不起作用的原因,我将不胜感激。我也尝试使用参数 numberOfTouches,结果相同。

class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
    // Declare instance variables here

    // We've pre-linked the IBOutlets
    @IBOutlet var heightConstraint: NSLayoutConstraint!
    @IBOutlet var sendButton: UIButton!
    @IBOutlet var messageTextfield: UITextField!
    @IBOutlet var messageTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        messageTableView.delegate = self
        messageTableView.dataSource = self

        //TODO: Set yourself as the delegate of the text field here:
        messageTextfield.delegate = self

        //TODO: Set the tapGesture here:
        //messageTableView.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTapped))
        messageTableView.addGestureRecognizer(tapGesture)

        //TODO: Register your MessageCell.xib file here:
        messageTableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "customMessageCell")
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell

        let messageArray = ["1","2","3"]
        cell.messageBody.text = messageArray[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.estimatedRowHeight = 100.0
        tableView.rowHeight = UITableViewAutomaticDimension
        return 3
    }

    @objc func tableViewTapped (){
        messageTableView.endEditing(true)
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        UIView.animate(withDuration: 0.5) {
            self.heightConstraint.constant = 380
            self.view.layoutIfNeeded()
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        UIView.animate(withDuration: 0.5) {
        self.heightConstraint.constant = 50
        self.view.layoutIfNeeded()
    }
}

尝试通过更新您的选择器方法将整个视图的 endEditing 设置为 true:

@objc func tableViewTapped (){
    view.endEditing(true)
}

您可能还想将 gestureRecognizer 添加到 view 本身而不是 tableView,因为它可能会因与 didSelectRowAt 方法重叠而导致更多问题。

如果这不起作用,请尝试在您的 viewDidLoad 中添加以下内容(在这种情况下,您不需要 gestureRecognizer):

messageTableView.keyboardDismissMode = .interactive