【发布时间】:2018-01-20 16:55:32
【问题描述】:
我的屏幕底部有 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。
-
@ArunGJ 是有效的..谢谢..你可以回答一下,所以我可以接受吗??