【发布时间】:2015-12-22 12:39:36
【问题描述】:
当键盘出现时,我使用以下代码向上移动视图。
这很好用,但我有一个问题,如果我点击一个文本字段并直接点击下一个文本字段,它会将我的视图向上移动两次。
我怎样才能让它只向上移动一次视图?
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
}
}
【问题讨论】:
-
我个人建议使用约束,而不是绝对值。另外我会使用子视图而不是向上移动整个视图。