鍵盤該怎麼收,是每個 iOS 新手都會踩到的問題。以下整理五種常見做法,可依畫面結構挑選最適合的一種。
1. 點擊編輯區以外的地方(UIView)
2. 點擊編輯區域以外的地方(UIControl)
3. 自製一個收起鍵盤的按鈕
4. 透過判斷輸入字元收起
5. 鍵盤遮蔽輸入區域的處理
最直覺的做法:不需要鍵盤時,點一下鍵盤與輸入區之外的空白處就收起來。可以覆寫 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]; }
最後實作按下後的行為,別忘了把按鈕本身移除:
-(void) hideKeyboard { [doneButton removeFromSuperview]; [myTextView resignFirstResponder]; }
若想讓使用者按下 return 換行時就收起鍵盤,必須先在類別的 @interface 區段宣告遵守對應協定。接著實作協定中的 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 中把 delegate 指向自己,程式才能找到實作協定方法的類別:
- (void)viewDidLoad { [super viewDidLoad]; myTextView.delegate = self; }
如果實作時遇到鍵盤把輸入框擋住的問題,可以透過 Core Graphic 的 Animation 功能,在鍵盤出現的同時移動編輯區域,把被遮住的元件推到可見位置。
以上就是 iOS 收起鍵盤的五種常見做法。選擇的原則很簡單:畫面有空白處就用第一、二種;沒有就自製按鈕;需要以換行鍵確認輸入完成時用第四種。謝謝大家對本站的支持!