iOS 提供了四個鍵盤通知,分別對應「將要出現、已經出現、將要隱藏、已經隱藏」。把前兩個用於做布局調整通常最合適,因為此時還來得及做動畫。
[[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,再判斷哪些子視圖會被遮擋,然後整體上移。
- (void)keyboardWillShow:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
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;
}
}
實用建議:與其手寫 begin/commit 動畫,不如直接讀取通知裡的鍵盤動畫時長與曲線參數,讓自定義動畫和系統鍵盤完全同步,視覺上會自然很多。
在 UITextField 和 UITextView 中,如何監聽到刪除鍵?網上很多方案是用代理判斷文本變化來間接推測,我覺得不靠譜——刪空之後再按刪除,代理就不會再回調了。
其實蘋果在系統協議裡已經寫得很清楚了:
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 就是刪除鍵的入口。只要寫一個子類並重寫這個方法,就能準確捕捉到每一次刪除操作,無論文本框是否已經為空。
以上就是鍵盤事件監聽的實例小結,希望對大家有所幫助。