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

iOS 鍵盤遮住 UITextField 的解法:只移動必要的高度

編輯:iOS 開發綜合

UITextField 被鍵盤遮住,是每個 iOS 開發者都會遇到的老問題。網路上方案不少,但各有缺陷:早期做法在 iOS 5 之後就失準了——因為鍵盤布局變了,中文輸入時候選字列固定在鍵盤上方,實際佔用的高度與以往不同。另一派方案則乾脆整個 view 往上推一個鍵盤高度,在部分情境下顯得過度。

以下做法在兩者之間取折衷:只把 view 往上移動「剛好被遮住的那一段高度」。

BaseViewController.h

#import <UIKit/UIKit.h>

@interface BaseViewController : UIViewController <UITextFieldDelegate> {
    UITextField *_checkText;   // 標識目前哪一個 UITextField 被點擊
}

@property (nonatomic) UITextField *checkText;

- (void)moveInputBarWithKeyboardHeight:(float)height
                          withDuration:(NSTimeInterval)duration;

@end

BaseViewController.m

#import "BaseViewController.h"

@implementation BaseViewController

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

    // iOS 5.0 新增:鍵盤高度變化通知
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(keyboardWillShow:)
                                                    name:UIKeyboardWillChangeFrameNotification
                                                  object:nil];
    }
#endif
}

#pragma mark - 開始編輯

// 實測這個方法會在 keyboardWillShow 之前被呼叫
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    _checkText = textField;   // 記錄被點擊的欄位
}

#pragma mark - 鍵盤彈出

- (void)keyboardWillShow:(NSNotification *)notification {
    if (nil == _checkText) {
        return;
    }

    NSDictionary *userInfo = [notification userInfo];

    // 鍵盤最終位置的 frame
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];

    // 動畫時間
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];

    // 計算被遮住的距離
    CGRect textFrame = _checkText.frame;
    float textY = textFrame.origin.y + textFrame.size.height;      // 欄位下緣距頂部
    float bottomY = self.view.frame.size.height - textY;           // 下緣距底部

    if (bottomY >= keyboardRect.size.height) {
        return;   // 本來就沒被遮住,不需移動
    }

    float moveY = keyboardRect.size.height - bottomY;
    [self moveInputBarWithKeyboardHeight:moveY withDuration:animationDuration];
}

#pragma mark - 鍵盤收起

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];

    [self moveInputBarWithKeyboardHeight:0.0 withDuration:animationDuration];
}

#pragma mark - 移動 view

- (void)moveInputBarWithKeyboardHeight:(float)height
                          withDuration:(NSTimeInterval)duration {
    CGRect rect = self.view.frame;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration];
    rect.origin.y = -height;
    self.view.frame = rect;
    [UIView commitAnimations];
}

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

@end

幾個值得注意的細節

  • 為什麼要記住 _checkText:一個畫面裡通常有多個輸入欄位,只有真正被點擊的那一個才需要判斷是否被遮住。用 textFieldDidBeginEditing: 記錄,比在 keyboardWillShow: 裡猜要可靠得多。
  • 用通知的 userInfo 而非硬編碼高度:UIKeyboardFrameEndUserInfoKey 給的是鍵盤的最終 frame,UIKeyboardAnimationDurationUserInfoKey 給的是動畫時長。用這兩個值搭配,view 的位移才會與鍵盤的彈出同步,不會出現「鍵盤先到位、畫面才慢慢移」的落差。
  • dealloc 記得移除 observer,否則控制器釋放後收到通知會崩潰。

更現代的替代方案是直接用 UIStackView 搭配 keyboardLayoutGuide 做約束綁定,或把輸入區放在 UITableView 中讓系統幫你滾動。但在需要維護的舊專案裡,上面這套手動位移的做法依然是最容易落地、副作用最小的選擇。

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