我试图在使用键盘显示时将文本字段上移,而在隐藏键盘时又将文本字段下移。因此,我在使用NotificationCenter.default.addObserver
,但这仅在充电时有效,而当我从充电器中取出时却不起作用,也就是说,它可能无法移动。请帮我解决这个问题。预先感谢
下面是我的代码:
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 -= 50
}
}
}
@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 += 50
}
}
}
答案 0 :(得分:0)
问题是您使用的是UIKeyboardFrameBeginUserInfoKey
而不是UIKeyboardFrameEndUserInfoKey
。
代码应为:
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
答案 1 :(得分:0)
如果self.view.frame.origin.y
是0
,则什么也没有发生。是吗?
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
// If `origin.y` is `0`, then do nothing.
if self.view.frame.origin.y != 0{
self.view.frame.origin.y -= 50
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
// If `origin.y` is `0` in `keyboardWillShow`,
// it will still be `0` here.
// So, do nothing.
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += 50
}
}
}