我有下面的设置。当键盘在屏幕上时,将textFields移动到键盘上方是一件好事。在那个时刻,如果用户关闭预测键盘,则高度无法重新调整到新的keyboardFrame.height + 20(键盘和textField之间的额外填充)。当键盘在屏幕上并且用户在预测开/关之间切换时,什么是重新调整scrollView.contentInset.bottom的好方法?
ViewDidLoad:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notificaiton:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
Oberservers:
//MARK: Keyboard Notifications
func keyboardWillShow(notificaiton: Notification) {
adjustKeyboardHeight(show: true, notification: notificaiton)
}
func keyboardWillHide(notification: Notification) {
adjustKeyboardHeight(show: false, notification: notification)
}
private func adjustKeyboardHeight(show: Bool, notification: Notification) {
let userInfo = notification.userInfo!
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
if show {
fgScrollView.contentInset.bottom = keyboardFrame.height + 20
} else {
fgScrollView.contentInset = UIEdgeInsets.zero
}
}
//MARK: TextField Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField {
nextTextField.becomeFirstResponder()
}
textField.resignFirstResponder()
return true
}
答案 0 :(得分:0)
添加keyboardWillChangeFrame
观察者,每次键盘框架改变时都会调用此标记
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(notificaiton:)), name: .UIKeyboardWillChangeFrame, object: nil)
func keyboardWillChangeFrame(notificaiton : Notification ) -> Void {
print("New frame of keyboard = \(notificaiton.userInfo?[UIKeyboardFrameEndUserInfoKey] ?? 0)")
}