簡體   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