只要畫面上有輸入框,就離不開鍵盤。鍵盤何時出現、多高、會遮住哪些元件,這些都得靠監聽通知來掌握。本文整理三個實務上最常遇到的題目:註冊鍵盤通知、讓版面隨鍵盤滑動、以及不靠 delegate 攔截刪除鍵。
鍵盤的「將要出現/已經出現/將要隱藏/已經隱藏」各有對應的通知名稱。差別在於 Will 系列適合搭配動畫(此時動畫曲線與系統一致),Did 系列則是真正完成後的狀態。
// 鍵盤即將出現
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
// 鍵盤已經出現
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardShow:)
name:UIKeyboardDidShowNotification
object:nil];
// 鍵盤即將隱藏
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
// 鍵盤已經隱藏
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardHide:)
name:UIKeyboardDidHideNotification
object:nil];
通知的 userInfo 裡帶著鍵盤最終的 frame,從中取出 y 值,就能知道鍵盤上緣落在哪裡。判斷每個子視圖的 maxY 是否會被遮住,若會,就把它往上推相同的距離。
- (void)keyboardWillShow:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
// 取出鍵盤最終的 frame,y 就是鍵盤上緣
CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat y = rect.origin.y;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
NSArray *subviews = [self subviews];
for (UIView *sub in subviews) {
CGFloat maxY = CGRectGetMaxY(sub.frame);
// 只有會被遮住的元件才需要上移
if (maxY > y - 2) {
sub.center = CGPointMake(CGRectGetWidth(self.frame) / 2.0,
sub.center.y - maxY + y - 2);
}
}
[UIView commitAnimations];
}
- (void)keyboardShow:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
}
- (void)keyboardWillHide:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
NSArray *subviews = [self subviews];
for (UIView *sub in subviews) {
// 被推上去的元件,回到垂直居中的位置
if (sub.center.y < CGRectGetHeight(self.frame) / 2.0) {
sub.center = CGPointMake(CGRectGetWidth(self.frame) / 2.0,
CGRectGetHeight(self.frame) / 2.0);
}
}
[UIView commitAnimations];
}
- (void)keyboardHide:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
}
記得在 dealloc 或 viewDidDisappear 中執行 removeObserver:,否則通知還在,物件卻已釋放,容易造成崩潰。
需要在 UITextField 或 UITextView 裡攔截「使用者按了刪除鍵」這件事時,網路上多數做法是用 delegate 比對字串變化,判斷上很不可靠。
其實蘋果早就把答案寫在 UITextInput 協定裡了:
NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextView : UIScrollView <UITextInput> @protocol UITextInput <UIKeyInput> @protocol UIKeyInput <UITextInputTraits> - (BOOL)hasText; - (void)insertText:(NSString *)text; - (void)deleteBackward; @end
寫得非常直白:-deleteBackward 就是刪除鍵的統一入口,不論是實體鍵盤的 backspace 還是螢幕鍵盤的刪除鍵,都會走到這裡。因此只要自己寫一個子類別,覆寫這個方法,就能精準攔下刪除動作:
@interface MyTextView : UITextView
@end
@implementation MyTextView
- (void)deleteBackward {
// 在這裡處理你的邏輯,例如攔下空字串時的刪除
NSLog(@"使用者按了刪除鍵");
[super deleteBackward];
}
@end
這種做法比在 shouldChangeCharactersInRange 裡猜「range 長度為 1 且替換字串為空」乾淨得多,也不會誤判中文輸入法候選期間的狀態。