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

iOS 鍵盤那些事:UITextField / UITextView 的收起與遮擋處理

編輯:iOS 開發綜合

在 iOS 開發裡,UITextField 與 UITextView 幾乎無所不在。預設情況下點擊輸入框就會彈出鍵盤,但如果使用者非得按下 return 才能收起鍵盤,體驗其實很差;而在小螢幕機型上,鍵盤還可能直接把輸入框蓋住。本文分三個部分把這些問題一次解決。

一、點擊空白處收起鍵盤

思路是監聽鍵盤的通知:鍵盤彈出時才掛上點擊手勢,鍵盤收起時把手勢移除,這樣就不會影響到頁面上其他需要點擊的元件。

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpForDismissKeyboard];
}
#pragma mark - 點擊空白處回收鍵盤
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene = [NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note) {
        [self.view addGestureRecognizer:singleTapGR];
    }];
    [nc addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note) {
        [self.view removeGestureRecognizer:singleTapGR];
    }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    // 讓 self.view 底下所有第一響應者一併放棄
    [self.view endEditing:YES];
}

二、按下鍵盤 return 收起鍵盤

#pragma mark - UITextViewDelegate
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [self.workLogTextView resignFirstResponder];
        return NO; // 攔下換行,避免多出一個空行
    }
    return YES;
}

注意:這段是 UITextView 的代理方法。若實際用的是 UITextField,改呼叫 textFieldShouldReturn: 即可,記得在類別宣告中遵守對應的代理協議。

三、處理鍵盤遮擋輸入框

如果頁面父視圖是 UIScrollView,最簡單的做法就是在開始編輯時把內容向上推,結束編輯時復位:

#pragma mark 鍵盤遮擋處理
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if (self.userInfo.isPhone4) {
        CGFloat offset_y = 0.f;
        if (textView.tag == CALL_CONTENT_TEXTFIRLD) {
            offset_y = 100.f;
        }
        CGPoint point = self.BackScrollView.contentOffset;
        point = CGPointMake(point.x, offset_y);
        [UIView animateWithDuration:0.25 animations:^{
            self.BackScrollView.contentOffset = point;
        }];
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    if (self.userInfo.isPhone4) {
        CGPoint point = self.BackScrollView.contentOffset;
        point = CGPointMake(point.x, 0);
        [UIView animateWithDuration:0.25 animations:^{
            self.BackScrollView.contentOffset = point;
        }];
    }
    return YES;
}

使用這段程式碼要留意兩點:類別需同時遵守 UIScrollViewDelegate 與文字輸入控件的代理協議;頁面的父容器必須是 UIScrollView,否則沒有 contentOffset 可調整。程式碼中的 self.BackScrollView 請替換成你專案裡實際的滾動視圖。

補充一個更通用的思路:如果不想為每個輸入框手寫偏移量,可以監聽 UIKeyboardWillChangeFrameNotification,取出鍵盤高度後計算需要上移的距離,這樣在各種螢幕尺寸與不同鍵盤(含第三方輸入法的候選列)下都更穩妥。

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