>我使用以下代码在键盘显示和隐藏时上下移动屏幕
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
它适用于所有设备,除了iPhone x(我认为问题是iPhone X底部浪费了空间(
问题是键盘大小在显示之前和之后发生变化,并导致视图向下,向下,向下......
谁能帮忙?
您还应该考虑安全区域插图
let endFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? CGRect.zero
let bottomSpace = keyboardValues.endFrame.maxY - keyboardValues.endFrame.minY - self.view.safeAreaInsets.bottom
而且你不应该是添加剂。这些通知可能会多次发布。使用绝对值。
在这里, 使用IQKeyboardManagerSwift
应用程序委托.swift设置
IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.enableAutoToolbar = false
在我的视图中控制器
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
print(#function)
if DeviceType.checkiPhoneX() {
IQKeyboardManager.shared.keyboardDistanceFromTextField = 40.0
}
return true
}
func textViewDidEndEditing(_ textView: UITextView) {
if DeviceType.checkiPhoneX() {
IQKeyboardManager.shared.keyboardDistanceFromTextField = 0.0
}
}
这就是我管理 X 键盘的方式。
希望这对您有所帮助。
使用 UIKeyboardFrameEndUserInfoKey而不是UIKeyboardFrameBeginUserInfoKey。