你需要注意键盘出现/消失的时候,并相应地设置tableView的contentInset。
在您的 TableViewController 类中创建两个函数作为键盘事件的响应者:
func keyBoardWillShow(notification: NSNotification) {
if let keyBoardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyBoardSize.height, right: 0)
self.tableView.contentInset = contentInsets
}
}
func keyBoardWillHide(notification: NSNotification) {
self.tableView.contentInset = UIEdgeInsets.zero
}
并在ViewDidLoad 和deinit 中注册/注销响应者:
override func viewDidLoad() {
super.viewDidLoad()
...
// register the responders
NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}