Hide keyboard Swift

I have a ViewController with a TableView and a lower view responsible for posting comments. I want to hide the keyboard by clicking on any place except my bottom view. But at the moment, the keyboard is hiding even when you click on the send message button, and the message is not sent.enter image description here

Upvotes: 0

Views: 231

Answers (2)

Alexander Volkov
Alexander Volkov

Reputation: 8407

You can do something like that:

    extension UITableView {

        open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.superview?.endEditing(true) // should be a path to top most view
            super.touchesBegan(touches, with: event)
        }
    }

Or you can create a subclass from UITableView and apply to that particular tableView.

Another variant is to add transparent overlay every time the keyboard appear, and add a tap action on it - to close the keyboard and remove the overlay, but in that case table will not be scrollable until you close the keyboard.

Upvotes: 2

override func hideKeyboard() {
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTap(gestureRecognizer:)))
    tapGesture.cancelsTouchesInView = false
    view.addGestureRecognizer(tapGesture)
}

@objc func tableViewTap(gestureRecognizer: UITapGestureRecognizer) {
    textInputBar.commentTextField.endEditing(true)
}

@objc func handleKeyboardNotifications(notification: Notification) {

    if let userInfo = notification.userInfo {
        guard let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
        print(keyboardFrame)
        let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
        bottomSendCommentViewConstraint.constant = isKeyboardShowing ? keyboardFrame.height - 83 : 5
        bottomTableViewConstraint.constant = isKeyboardShowing ? keyboardFrame.height - 83 : 0

        UIView.animate(withDuration: 0, delay: 0, options: .curveEaseOut, animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}

private func keyboardNotifications() {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(handleKeyboardNotifications(notification:)),
                                           name: UIResponder.keyboardWillShowNotification,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(handleKeyboardNotifications(notification:)),
                                           name: UIResponder.keyboardWillHideNotification,
                                           object: nil)
}

Upvotes: 0

Related Questions