我有一个包含表格单元格的表格视图。每个单元格都有一个文本字段。我有以下代码来防止底部的几个单元格被键盘阻止
@objc func keyboardWillShow(_ notification:Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
}
}
@objc func keyboardWillHide(notification: NSNotification) {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(TransactionViewController.keyboardWillHide), name: UIApplication.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TransactionViewController.keyboardWillShow), name: UIApplication.keyboardWillChangeFrameNotification, object: nil)
}
keyboardWillHide
函数按预期工作。然而,当键盘被隐藏时,表确实会从底部反弹,从而不会显示额外的空白(这正是我想要的(。我不喜欢的是,你仍然可以在桌子上向下滚动到第一次显示键盘的contentInset。有没有办法让键盘消失后,你不能向下滚动到表格底部?
更换
keyboardFrameBeginUserInfoKey
带有
keyboardFrameEndUserInfoKey
@objc func keyboardWillShow(_ notification:Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
}
}
@objc func keyboardWillHide(notification: NSNotification) {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(TransactionViewController.keyboardWillHide), name: UIApplication.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TransactionViewController.keyboardWillShow), name: UIApplication.keyboardWillShowNotification, object: nil)
}