UIKitUIKeyboardWillShowNotification
は、キーボードを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:
。
dealloc
またはviewWillDisappear:animated:
:で登録を解除する必要があります
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
もちろん、トリッキーなビットはkeyboardWillHideOrShow:
メソッドにあります。まず、通知からアニメーションパラメータを抽出します。
- (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];
}