系統鍵盤高度因輸入法類型(拼音、手寫、Emoji、第三方鍵盤)而異,且支持分屏、懸浮模式。唯有監聽 UIKeyboardWillChangeFrameNotification 並同步動畫曲線,才能實現輸入區域「像素級跟隨」。
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillChangeFrame:)
name:UIKeyboardWillChangeFrameNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillChangeFrameNotification
object:nil];
}
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
NSDictionary *info = notification.userInfo;
// 動畫參數
CGFloat duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve = [info[UIKeyboardAnimationCurveUserInfoKey] intValue];
// 鍵盤框架(螢幕坐標系)
CGRect beginFrame = [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect endFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 計算 Y 軸偏移量
CGFloat yOffset = endFrame.origin.y - beginFrame.origin.y;
// 更新輸入區域 Frame(或 Auto Layout 約束)
[UIView animateWithDuration:duration
delay:0
options:curve << 16 // 關鍵:轉換 AnimationCurve 到 UIViewAnimationOptions
animations:^{
self.inputTextField.frame = CGRectOffset(self.inputTextField.frame, 0, yOffset);
self.moreButton.frame = CGRectOffset(self.moreButton.frame, 0, yOffset);
// 或更新底部約束:self.bottomConstraint.constant = -endFrame.size.height;
} completion:nil];
}
UIViewAnimationCurve 需左移 16 位轉為 UIViewAnimationOptions(curve << 16),否則動畫會「掉幀」或「彈跳」。view.safeAreaInsets.bottom 修正。UITextFieldDelegate 記錄 firstResponder,針對性調整對應視圖。將上述邏輯封裝為 KeyboardManager 單例或 UIViewController 分類,提供:
@protocol KeyboardTracking
- (void)keyboardWillChangeFrame:(CGRect)endFrame duration:(CGFloat)duration curve:(UIViewAnimationCurve)cve;
@end
// 使用時僅需遵循協議並實現一個方法
- (void)keyboardWillChangeFrame:(CGRect)endFrame duration:(CGFloat)duration curve:(UIViewAnimationCurve)curve {
self.bottomConstraint.constant = endFrame.size.height - self.view.safeAreaInsets.bottom;
[UIView animateWithDuration:duration delay:0 options:curve << 16 animations:^{
[self.view layoutIfNeeded];
} completion:nil];
}
UIKeyboardWillShow/HideNotification → 無法處理鍵盤類型切換、分屏高度變化。UIKeyboardWillChangeFrameNotification 覆蓋所有場景。一套代碼應對所有鍵盤形態,才是專業工程師的標準。