swift 键盘向上移动两次
swift keyboard moves up twice
我使用以下代码在键盘出现时向上移动视图。
这工作正常,但我有一个问题,如果我点击一个文本字段并直接点击下一个文本字段,它会将我的视图向上移动两次。
我怎样才能让它只向上移动一次视图?
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
func keyboardWillShow(notification: NSNotification) {
print(self.view.frame.origin.y)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y -= keyboardSize.height
}
print(self.view.frame.origin.y)
}
func keyboardWillHide(notification: NSNotification) {
print("is dissapaering now")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y += keyboardSize.height
}
}
听起来你应该在再次显示之前检查键盘是否已经显示。创建一个新的 Bool 变量来跟踪状态,并且仅在 Bool 值为 false 时才移动视图。
我使用以下代码在键盘出现时向上移动视图。
这工作正常,但我有一个问题,如果我点击一个文本字段并直接点击下一个文本字段,它会将我的视图向上移动两次。
我怎样才能让它只向上移动一次视图?
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
func keyboardWillShow(notification: NSNotification) {
print(self.view.frame.origin.y)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y -= keyboardSize.height
}
print(self.view.frame.origin.y)
}
func keyboardWillHide(notification: NSNotification) {
print("is dissapaering now")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y += keyboardSize.height
}
}
听起来你应该在再次显示之前检查键盘是否已经显示。创建一个新的 Bool 变量来跟踪状态,并且仅在 Bool 值为 false 时才移动视图。