簡體   English   中英

無法使用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)
}

另外,您可能希望添加而不是tableView而不是tableViewview手勢本身,因為與didSelectRowAt方法重疊可能會引起進一步的問題。

如果這樣不起作用,請嘗試在viewDidLoad添加以下內容(在這種情況下,您將不需要gestureRecognizer ):

messageTableView.keyboardDismissMode = .interactive

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM