如果 UITableViewController 的自动滚动不适用于单元格中的 UITextField 或滚动异常,请执行以下步骤。Swift 5 iOS 13.2 测试 100%
首先实现viewWillAppear但不要调用super.viewWillAppear(这将停止自动滚动)
override func viewWillAppear(_ animated: Bool) {
}
然后让我们手动进行滚动。
override func viewWillAppear(_ animated: Bool) {
//Notification center observers
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)),
name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)),
name: UIResponder.keyboardWillHideNotification, object: nil)
}
//keybord show action
@objc func keyboardWillShow(notification: Notification) {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: notification.getKeyBoardHeight, right: 0)
}
//keyboard hide action
@objc func keyboardWillHide(notification: Notification) {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
extension Notification {
var getKeyBoardHeight: CGFloat {
let userInfo: NSDictionary = self.userInfo! as NSDictionary
let keyboardFrame: NSValue = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
return keyboardRectangle.height
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}