您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 學習筆記:輸入框上移與鍵盤收起動畫的兩種寫法

編輯:iOS 開發綜合

做 iOS 開發時幾乎一定會碰到這個場景:鍵盤一彈出就蓋住 UITextField,使用者看不到自己輸入的內容。解法是把視圖往上推一段距離,輸入結束後再滑回原位,點擊畫面任意處則收起鍵盤。

以下整理兩種常見寫法。兩者都需要在 .h 中採用 UITextFieldDelegate 並設定 delegate,這部分從略。

寫法一:在編輯開始與結束時分別位移

優點是直觀,缺點是上下兩段程式碼幾乎重複。

// UITextField 進入編輯時呼叫
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.20];
    [UIView setAnimationBeginsFromCurrentState:YES];
    // 視圖上移
    self.view.frame = CGRectMake(self.view.frame.origin.x,
                                 self.view.frame.origin.y - 100,
                                 self.view.frame.size.width,
                                 self.view.frame.size.height);
    [UIView commitAnimations];
}

// UITextField 結束編輯時呼叫
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.20];
    [UIView setAnimationBeginsFromCurrentState:YES];
    // 視圖歸位
    self.view.frame = CGRectMake(self.view.frame.origin.x,
                                 self.view.frame.origin.y + 100,
                                 self.view.frame.size.width,
                                 self.view.frame.size.height);
    [UIView commitAnimations];
}

寫法二:抽出共用方法並用旗標控制方向

把位移邏輯集中在一處,編輯開始與結束都呼叫同一個方法,只是傳入的 up 不同。這樣位移距離只需要維護一個地方。

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self animateTextField:textField up:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self animateTextField:textField up:NO];
}

- (void)animateTextField:(UITextField *)textField up:(BOOL)up {
    const int movementDistance = 100;      // 位移距離,可依需要調整
    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.20];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

讓鍵盤收起

覆寫 touchesBegan:withEvent:,在使用者點擊背景時送出 endEditing 訊息:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

endEditing: 會讓視圖層級中的第一響應者放棄焦點,因此不管焦點在哪個輸入框都能一次收起,比逐一呼叫 resignFirstResponder 方便。

更進一步的做法

以上兩種寫法都把位移距離寫死為 100,實作簡單,但遇到鍵盤高度不同(橫屏、第三方鍵盤)或畫面中有多個輸入框時就不夠用。更穩健的作法是監聽 UIKeyboardWillShowNotification,從通知的 userInfo 取出鍵盤的 frame,計算「輸入框底端與鍵盤頂端的重疊量」,只位移剛好足夠的距離。同時也可以把 UIView 的動畫改為配合鍵盤動畫的 duration 與 curve,讓兩者同步移動,視覺上會自然許多。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved