鍵盤的顯示與隱藏是 iOS 開發中的基礎環節,以下彙整五種實作思路,可依畫面結構與互動需求挑選最合適的一種。
這是最直覺的做法:當不再需要鍵盤時,只要點擊鍵盤與編輯區以外的區域即可收起。以下程式碼放在 UIView 內建的觸碰事件方法中:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (![myTextView isExclusiveTouch]) {
[myTextView resignFirstResponder];
}
}
使用此方式時,畫面的 Custom Class 必須是 UIView。
原理與上一種相同,但若你的觸碰事件已經寫滿程式碼,可以改用 UIControl 的 Touch Up Inside 事件來收起鍵盤,只要把下列方法連接到該事件即可:
- (IBAction)dismissKeyboard:(id)sender {
[myTextView resignFirstResponder];
}
使用此方式時,畫面的 Custom Class 必須是 UIControl。
當畫面上沒有可點擊的空白區域時,可以自己製作一個按鈕來收起鍵盤。由於按鈕需要在鍵盤出現時才顯示,因此要借助 NSNotificationCenter 判斷鍵盤狀態。首先在 viewDidLoad 中註冊通知:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doneButtonshow:) name:UIKeyboardDidShowNotification object:nil];
}
每當鍵盤出現,便會自動呼叫 doneButtonshow: 方法,接著在其中定義按鈕的外觀與行為:
-(void) doneButtonshow: (NSNotification *)notification {
doneButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
doneButton.frame = CGRectMake(0, 228, 70, 35);
[doneButton setTitle:@"完成編輯" forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(hideKeyboard) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:doneButton];
}
最後實作按下按鈕時的 hideKeyboard 方法,別忘了移除按鈕:
-(void) hideKeyboard {
[doneButton removeFromSuperview];
[myTextView resignFirstResponder];
}
若想以特定字元(例如 return 換行符)觸發收起,必須先在類別的 @interface 區段採用 UITextViewDelegate 協定,然後實作 textView:shouldChangeTextInRange:replacementText: 方法。該方法會在字元輸入時觸發,回傳的 BOOL 值決定該字元是否生效:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"]) {
[myTextView resignFirstResponder];
return NO;
}
return YES;
}
最後別忘了在 viewDidLoad 中將 UITextView 的 delegate 指向自己,程式才能找到實作協定的類別:
- (void)viewDidLoad {
[super viewDidLoad];
myTextView.delegate = self;
}
如果實作時遇到鍵盤遮住編輯區的狀況,可以透過 Core Graphics 的 Animation 功能,在鍵盤出現的同時移動編輯區,藉此解決遮蔽問題。
這些鍵盤處理技巧在日常開發中經常派上用場,掌握它們能讓表單互動更加順暢,希望對你的開發有所幫助。