[英]Hide keyboard Swift
你可以這樣做:
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.