简体   繁体   中英

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. 在此处输入图片说明

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM