鍵盤彈出或收起時,可透過 NSNotificationCenter 監聽 UIKeyboardWillShowNotification 與 UIKeyboardWillHideNotification,並在通知中取得鍵盤尺寸、動畫時間與曲線。
- (void)keyboardWillShow:(NSNotification *)note {
CGRect keyboardBounds = [[note.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
CGRect frame = self.editView.frame;
frame.origin.y = self.view.bounds.size.height - keyboardBounds.size.height - frame.size.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:[duration doubleValue]];
[UIView setAnimationCurve:[curve intValue]];
self.editView.frame = frame;
[UIView commitAnimations];
}
收起鍵盤時,可將輸入框移回畫面下方,並使用相同的動畫參數,讓視覺體驗更一致。