繁体   English   中英

隐藏键盘 Swift

[英]Hide keyboard Swift

我有一个带有 TableView 的 ViewController 和一个负责发布评论的较低视图。 我想通过单击除底部视图以外的任何地方来隐藏键盘。 但是目前,即使您单击发送消息按钮,键盘也是隐藏的,并且没有发送消息。 在此处输入图片说明

你可以这样做:

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

或者您可以从UITableView创建一个子类并应用于该特定的 tableView。

另一种变体是在每次键盘出现时添加透明覆盖,并在其上添加点击操作 - 关闭键盘并移除覆盖,但在这种情况下,除非您关闭键盘,否则表格将无法滚动。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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