2015-09-24 48 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變量,並且只在布爾值爲假時才移動視圖。