您可以多次设置 contentInset 吗?

Can you set contentInset more than once?

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

@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 函数按预期工作。但是,当键盘被隐藏时,table 会弹回到底部,导致不会显示额外的空白(这正是我想要的)。我不喜欢的是您仍然可以在 table 上向下滚动到首次显示键盘的 contentInset。有没有办法让它在键盘消失后,你不能向下滚动通过 table 的底部?

替换

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