我有一个包含四个单元格的 tableView。每个单元格都有一个带有长长文本的 UITextView。当用户开始编辑文本时,键盘出现并且 tableView 向上滚动。我希望它与键盘外观同时发生(就像在Apple Notes应用程序中一样)。不过好像有点延迟。
它是如何发生的:
我希望它如何发生:
这是我的代码:
private func addKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc
private func keyboardWillShow(notification: Notification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
}
@objc
private func keyboardWillHide() {
tableView.contentInset = .zero
}
PS:最初我尝试使用 SwiftUI 来实现这种行为,但滚动看起来更混乱。如果有人可以建议 SwiftUI 解决方案,我们将不胜感激。平安✌️
根据我的经验,您应该将更新 UITableView 内容插入的代码包装在 UIView.animate 块中。这里,神奇的数字 0.25 是键盘完全显示在屏幕上的时间。
private func addKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc
private func keyboardWillShow(notification: Notification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
UIView.animate(withDuration: 0.25, animations: {
self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
})
}
@objc
private func keyboardWillHide() {
UIView.animate(withDuration: 0.25, animations: {
self.tableView.contentInset = .zero
})
}