我的屏幕底部有 2 个按钮。我实现了下面的代码以显示和隐藏键盘,但不覆盖底部的 2 个按钮。
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
//here will hide the keyboard when tap the text view 2 times
let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard))
self.statusTextView.addGestureRecognizer(tap)
}
@objc func hideKeyBoard(sender: UITapGestureRecognizer? = nil){
statusTextView.endEditing(true)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if let window = self.view.window?.frame {
// We're not just minusing the kb height from the view height because
// the view could already have been resized for the keyboard before
self.view.frame = CGRect(x: self.view.frame.origin.x,
y: self.view.frame.origin.y,
width: self.view.frame.width,
height: window.origin.y + window.height - keyboardSize.height)
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let viewHeight = self.view.frame.height
self.view.frame = CGRect(x: self.view.frame.origin.x,
y: self.view.frame.origin.y,
width: self.view.frame.width,
height: viewHeight + keyboardSize.height)
}
}
通过上面的代码,我成功地显示和隐藏了键盘,没有覆盖底部的任何元素。
但是奇怪的事情发生了,当我点击 textview
2 次时,键盘隐藏了但是屏幕底部的 2 按钮消失了。
所以我的问题是,为什么隐藏键盘时元素会消失?以及如何解决??
最佳答案
使用 UIKeyboardFrameEndUserInfoKey
而不是 UIKeyboardFrameBeginUserInfoKey
因为 UIKeyboardFrameBeginUserInfoKey
可以在 keyboardWillShow
和 keyboardWillHide< 中返回不同的值
UIKeyboardFrameBeginUserInfoKey
– 当前键盘状态改变开始时的键盘框架。
UIKeyboardFrameEndUserInfoKey
– 当前键盘状态更改结束时的键盘框架。
关于ios - 隐藏键盘 Swift 4 后 View 底部的元素消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353774/