iOS全局处理键盘事件

注册监听键盘事件的通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[[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];

在键盘将要出现和隐藏的回调中,加入动画

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
- (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;
}
}