鍵盤何時該收起,是每個 iOS 新手都會遇到的問題。以下整理幾種實用做法。
1. 點擊編輯區以外的位置(UIView)
這是最直覺的做法:不再需要鍵盤時,點畫面上其他地方就收起。以下程式碼放在 UIView 內建的觸碰事件方法中:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (![myTextView isExclusiveTouch]) {
[myTextView resignFirstResponder];
}
}
使用這個方式的前提是:該畫面的 Custom Class 必須是 UIView。
2. 點擊編輯區以外的位置(UIControl)
思路相同,但如果你的 touchesEnded 已經寫滿了其他邏輯,可以改用 UIControl 的 Touch Up Inside 事件,把下面的方法連到該事件即可:
- (IBAction)dismissKeyboard:(id)sender {
[myTextView resignFirstResponder];
}
使用這個方式的前提是:該畫面的 Custom Class 必須是 UIControl。
3. 自製「完成」按鈕
如果畫面上沒有可點擊的空白處,自己做一顆按鈕來收鍵盤也不錯。因為按鈕只該在鍵盤出現時顯示,所以要靠 NSNotificationCenter 判斷鍵盤狀態。
先在 viewDidLoad 註冊通知:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doneButtonshow:)
name:UIKeyboardDidShowNotification
object:nil];
}
接著實作顯示按鈕的方法:
- (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];
}
最後是按下按鈕後的處理,記得把按鈕移除,否則下次鍵盤再出現會疊成兩顆:
- (void)hideKeyboard {
[doneButton removeFromSuperview];
[myTextView resignFirstResponder];
}
補充:更好的做法是搭配 UIKeyboardWillShowNotification/WillHideNotification 成對處理,並在 dealloc 中移除觀察者;或者乾脆用 inputAccessoryView 掛一條工具列,讓系統幫你管理顯示時機。
4. 攔截特定輸入字元
若想按下 return(換行)就收鍵盤,要先在類別中採用 UITextViewDelegate 協定,然後實作:
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"]) {
[myTextView resignFirstResponder];
return NO;
}
return YES;
}
別忘了在 viewDidLoad 中把 delegate 指向自己,否則方法永遠不會被呼叫:
- (void)viewDidLoad {
[super viewDidLoad];
myTextView.delegate = self;
}
5. 鍵盤遮住輸入框怎麼辦
如果鍵盤彈出後把輸入框擋住,可以監聽鍵盤高度變化,用 Animation 把輸入框往上推。實作時請以 UIKeyboardWillChangeFrameNotification 回呼中的最終 frame 為準,並記得在鍵盤收起時把位移還原。
總結
這幾種情況在開發中幾乎都會遇到,但細節不少。希望這份整理能幫大家少踩幾個坑。