萬盛學電腦網

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

iOS 虛擬鍵盤上動態添加「完成/隱藏」按鈕:跟隨高度變化的完整實現

許多輸入密集型 App(即時通訊、表單)會在鍵盤上方浮動一個「完成」按鈕,點擊收起鍵盤。難點在於鍵盤高度動態變化(中英切換、手寫、Emoji、第三方鍵盤),按鈕必須實時跟隨位置。

核心架構

  1. 監聽 UIKeyboardWillShowNotification / UIKeyboardWillHideNotification(或統一用 UIKeyboardWillChangeFrameNotification)。
  2. 從 userInfo 獲取鍵盤終態 Frame(螢幕坐標系)。
  3. 在主視圖或 Window 上添加按鈕,Frame 底部對齊鍵盤頂部。
  4. 鍵盤隱藏時隱藏按鈕(不移除,避免釋放崩潰)。

完整實現代碼

1. 註冊通知

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

2. 鍵盤彈出:創建/顯示/定位按鈕

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    CGRect keyboardEndFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardEndFrame.size.height;
    CGFloat duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [info[UIKeyboardAnimationCurveUserInfoKey] intValue];
    
    // 懶加載按鈕
    if (!self.doneButton) {
        self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.doneButton setImage:[UIImage imageNamed:@"keyboard_done"] forState:UIControlStateNormal];
        [self.doneButton addTarget:self action:@selector(dismissKeyboard:) forControlEvents:UIControlEventTouchUpInside];
        self.doneButton.frame = CGRectMake(0, 0, 60, 44); // 寬度自適應或固定
    }
    
    // 計算按鈕 Frame:右對齊,底部貼鍵盤頂部
    CGRect btnFrame = self.doneButton.frame;
    btnFrame.origin.x = self.view.bounds.size.width - btnFrame.size.width;
    btnFrame.origin.y = self.view.bounds.size.height - keyboardHeight - btnFrame.size.height;
    
    // 同步動畫
    [UIView animateWithDuration:duration delay:0 options:curve << 16 animations:^{
        if (self.doneButton.superview == nil) {
            [self.view addSubview:self.doneButton]; // 或 [UIApplication sharedApplication].keyWindow
        }
        self.doneButton.frame = btnFrame;
        self.doneButton.hidden = NO;
    } completion:nil];
}

3. 鍵盤收起:隱藏按鈕

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    CGFloat duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [info[UIKeyboardAnimationCurveUserInfoKey] intValue];
    
    [UIView animateWithDuration:duration delay:0 options:curve << 16 animations:^{
        self.doneButton.hidden = YES;
        // 不要 removeFromSuperview 或 release!會導致動畫中途視圖消失崩潰
    } completion:nil];
}

4. 按鈕動作:收起鍵盤

- (void)dismissKeyboard:(id)sender {
    [self.view endEditing:YES]; // 遞歸讓所有子視圖 resignFirstResponder
}

關鍵技術細節

  • 坐標系:通知 Frame 為**螢幕坐標系**,直接用 self.view.bounds 計算相對位置最可靠。
  • 動畫曲線同步: curve << 16 轉換為 UIViewAnimationOptions,保證按鈕與鍵盤同步移動。
  • 按鈕生命周期:懶加載創建,**隱藏而不銷毀**,dealloc 時統一釋放,避免動畫過程中釋放導致 EXC_BAD_ACCESS。
  • 輸入視圖切換:同一通知處理中英鍵盤切換、Emoji 面板展開/收起等高度變化。
  • 安全區適配:iPhone X 系列底部 Home Indicator 高度需疊加:btnFrame.origin.y -= self.view.safeAreaInsets.bottom;

現代封裝:KeyboardAccessoryView

更標準的做法是設置 UITextField.inputAccessoryView,系統自動管理顯示/隱藏/位置:

UIToolbar *accessory = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 0, 44)];
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyboard:)];
accessory.items = @[flex, done];
self.textField.inputAccessoryView = accessory;

**優勢:零代碼管理位置、自動適配分屏/懸浮鍵盤、支持多輸入框共用/獨立配件。**

總結

手動浮動按鈕適合高度定制化需求;標準場景**首選 inputAccessoryView**,零維護成本、系統級可靠性。

copyright © 萬盛學電腦網 all rights reserved