2017-05-16 62 views
0

我的主視圖底部有一個按鈕,我想在鍵盤顯示時使用鍵盤進行動畫處理。使用鍵盤顯示的動畫效果(按鈕)

我的按鈕設置像這樣在我的故事板的限制:

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myConstraint; 

添加時鍵盤顯示通知:

enter image description here

我已經在代碼鏈接的約束:

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardWillShow:) 
              name:UIKeyboardWillShowNotification 
              object:nil]; 

這裏是keyboardWillShow實現:

- (void)keyboardWillShow: (NSNotification *)notification { 
    NSDictionary *dictionary = notification.userInfo; 
    CGRect keyboardFrame = [dictionary[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 

    [UIView animateWithDuration:1.0f animations:^{ 
     self.myConstraint.constant = keyboardFrame.size.height + 18; 
    }]; 
} 

雖然它的工作原理,按鈕不會動畫,而是立即設置在視圖上新的位置。我試圖添加一個完成塊來查看會發生什麼,實際上完成是立即調用,而不是等待一秒鐘,因爲它應該...

什麼是錯?謝謝你的幫助。

回答

3

需要動畫是由約束變化引發的佈局事情....

self.myConstraint.constant = keyboardFrame.size.height + 18; 
[self.view setNeedsUpdateConstraints]; 

[UIView animateWithDuration:1.0f animations:^{ 
    [self.view layoutIfNeeded]; 
}]; 
+0

明白了!謝謝。 – Someday

0

我想你錯過layoutIfNeedUIView你想用新的約束值更新。

你應該嘗試一下。

+0

我嘗試過,但它不會爲你的答案工作 – Someday

0

儘量減少動畫延遲到0.3。鍵盤的速度動畫比您的按鈕的速度動畫更大。

您還需要將setNeedsLayout添加到您的按鈕。

+0

感謝。我可以通過danh回答完成,並且關於動畫延遲,我通過檢索鍵盤隱藏/顯示持續時間爲NSNumber來改進它:'NSNumber * duration = dictionary [UIKeyboardAnimationDurationUserInfoKey]',然後像這樣使用它:'animateWithDuration :[duration doubleValue]'。 – Someday

+0

這是一個好主意。謝謝。 – pluzzmo