您可以多次设置contentInset吗?

时间:2018-11-12 21:31:09

标签: ios swift uitableview nsnotificationcenter uikeyboard

我有一个带有表格单元格的表格视图。每个单元格都有一个文本字段。我有以下代码来防止底部的几个单元格被键盘阻塞

@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。有没有一种方法可以使键盘消失后,您无法向下滚动通过表格底部?

1 个答案:

答案 0 :(得分:2)

替换

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