在viewWillAppear中你UIKeyboardWillShow和UIKeyboardWillHide註冊通知:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
然後keyboardWillShow你鍵盤的框架,改變的tableView
func keyboardWillShow(notification: Notification) {
guard let keyboardFrame = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return }
let convertedFrame = view.convert(keyboardFrame, from: nil)
tableView.contentInset.bottom = convertedFrame.height
}
然後keyboardWillHide你改變的插圖底部插入回到0,並且如果需要的話,將tableView滾動回特定行。這將它滾動回位於tableView頂部的第一行。
func keyboardWillHide(notification: Notification) {
tableView.contentInset.bottom = 0
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
}
這也是一個很好的方法來做到這一點,因爲它讓你的textField代理與影響佈局的代碼保持一致。
我相信我讀的地方,你不需要刪除自己觀察員某些通知,其中包括鍵盤通知,但爲了穩妥起見,你應該把這些在viewWillDisappear或DEINIT視情況
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil)
// If you don't have any other notifications you wan't to keep observing you can remove yourself from all observers by using this one line
// NotificationCenter.default.removeObserver(self)
}
可以請你告訴我表單是動態的還是靜態的,如果是靜態的,那麼就有很簡單的方法來實現它,而不需要任何代碼。 –
我已經使用[IQKeyboardManager](https://github.com/hackiftekhar/IQKeyboardManager)來移動文本框,以防止它們被阻止。到目前爲止,它對我來說非常有用。 – NerdsGeeksGurus
使用鍵盤通知來處理此類問題 –