Не удается зарегистрировать касание на экране с помощью tapGestureRecognizer - PullRequest
0 голосов
/ 12 января 2019

Я пытаюсь создать приложение для чата с использованием 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()
    }
}

1 Ответ

0 голосов
/ 12 января 2019

Попробуйте установить значение endEditing всего представления, обновив свой метод выбора:

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

Также вы можете захотеть добавить gestRecognizer к самому view вместо tableView, потому что это может вызвать дальнейшие проблемы при наложении метода didSelectRowAt.

Если это не сработает, попробуйте добавить следующее в viewDidLoad (В этом случае вам не понадобится gestureRecognizer):

messageTableView.keyboardDismissMode = .interactive
...