UIKit在顯示鍵盤時發帖UIKeyboardWillShowNotification
,在隱藏鍵盤時發帖UIKeyboardWillHideNotification
。這些通知包含您爲使UITextField
正確動畫所需的一切。
假設您的UITextField
位於名爲myTextField
的屬性中。
首先,您需要在某處註冊通知。你在哪裏註冊取決於什麼對象負責移動myTextField
。在我的項目,該領域的上海華負責,因爲我從筆尖加載我的UI,我這樣做是在上海華的awakeFromNib
:
- (void)awakeFromNib
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideOrShow:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideOrShow:) name:UIKeyboardWillShowNotification object:nil];
}
如果使用UIViewController
左右移動領域,你可能會想要在viewWillAppear:animated:
中做到這一點。
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
當然棘手位是keyboardWillHideOrShow:
方法:
你應該在你dealloc
或viewWillDisappear:animated:
註銷。首先,我從通知中提取動畫參數:
- (void)keyboardWillHideOrShow:(NSNotification *)note
{
NSDictionary *userInfo = note.userInfo;
NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
的keyboardFrame
是全局座標系統相同。我需要的幀轉換到同一座標系myTextField.frame
,並且myTextField.frame
是myTextField.superview
座標系中:
CGRect keyboardFrameForTextField = [self.myTextField.superview convertRect:keyboardFrame fromView:nil];
接下來,我計算,我想myTextField
移動到框架。新框架的底部邊緣應等於鍵盤的框架的頂邊:
CGRect newTextFieldFrame = self.myTextField.frame;
newTextFieldFrame.origin.y = keyboardFrameForTextField.origin.y - newTextFieldFrame.size.height;
最後,我動畫myTextField
其新幀,使用相同的動畫參數,該鍵盤使用:
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | curve animations:^{
self.myTextField.frame = newTextFieldFrame;
} completion:nil];
}
這一切放在一起:
- (void)keyboardWillHideOrShow:(NSNotification *)note
{
NSDictionary *userInfo = note.userInfo;
NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect keyboardFrameForTextField = [self.myTextField.superview convertRect:keyboardFrame fromView:nil];
CGRect newTextFieldFrame = self.myTextField.frame;
newTextFieldFrame.origin.y = keyboardFrameForTextField.origin.y - newTextFieldFrame.size.height;
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | curve animations:^{
self.myTextField.frame = newTextFieldFrame;
} completion:nil];
}
謝謝。謝謝。謝謝。謝謝。稍作修改,我就可以工作,它看起來非常漂亮。 – iosfreak 2012-01-05 21:34:31
@rob mayoff問題是當我有一個'UITabBar'。當鍵盤將「UITextField」隱藏在「UITabBar」下面時。爲什麼? – 2012-02-05 20:41:28
如果您有一個標籤欄,那麼當鍵盤隱藏時,您需要根據標籤欄的框架而不是鍵盤的框架來計算'newTextFieldFrame'。 – 2012-02-05 21:30:04