2015-09-24 51 views
0

我使用以下代码在键盘出现时向上移动视图。 这工作正常,但我有问题,如果我在文本字段上点击并直接点击下一个文本框,它会将我的视图向上移动两次。
我怎样才能让它只移动一次?快速键盘向上移动两次

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 
    } 
} 
+0

我个人建议使用约束,而不是绝对值。另外,我会使用子视图而不是将整个视图向上移动。 –

回答

1

这听起来像你应该检查键盘是否已经显示再次显示之前。创建一个跟踪状态的新Bool变量,并且只在布尔值为假时才移动视图。