萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 鍵盤高度變化完美適配:基於 UIKeyboardWillChangeFrameNotification 的通用方案

系統鍵盤高度因輸入法類型(拼音、手寫、Emoji、第三方鍵盤)而異,且支持分屏、懸浮模式。唯有監聽 UIKeyboardWillChangeFrameNotification 並同步動畫曲線,才能實現輸入區域「像素級跟隨」。

核心實現

1. 註冊/註銷通知

- (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];
}

2. 統一處理彈出/收起/高度變化

- (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),否則動畫會「掉幀」或「彈跳」。
  • 坐標系統一:通知中的 Frame 始終是 **螢幕坐標系**,直接計算差值最可靠。
  • 安全區適配:iPhone X 系列底部 Home Indicator 區域需額外考慮,使用 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 → 無法處理鍵盤類型切換、分屏高度變化。
  • ❌ 硬編碼鍵盤高度(216/253/264/291/346...) → 設備、輸入法、系統版本全不同。
  • ❌ 忽略動畫曲線 → 視覺抖動,體驗極差。
  • ✅ 單一通知 UIKeyboardWillChangeFrameNotification 覆蓋所有場景。

一套代碼應對所有鍵盤形態,才是專業工程師的標準。

copyright © 萬盛學電腦網 all rights reserved