1、注册监听键盘事件的通知
1 | [[NSNotificationCenter defaultCenter] addObserver:self |
2 | selector:@selector(keyboardWillShow:) |
3 | name:UIKeyboardWillShowNotification |
4 | object:nil]; |
5 | |
6 | [[NSNotificationCenter defaultCenter] addObserver:self |
7 | selector:@selector(keyboardShow:) |
8 | name:UIKeyboardDidShowNotification |
9 | object:nil]; |
10 | |
11 | [[NSNotificationCenter defaultCenter] addObserver:self |
12 | selector:@selector(keyboardWillHide:) |
13 | name:UIKeyboardWillHideNotification |
14 | object:nil]; |
15 | |
16 | [[NSNotificationCenter defaultCenter] addObserver:self |
17 | selector:@selector(keyboardHide:) |
18 | name:UIKeyboardDidHideNotification |
19 | object:nil]; |
2、在键盘将要出现和隐藏的回调中,加入动画。
1 | - (void)keyboardWillShow:(NSNotification *)notif { |
2 | if (self.hidden == YES) { |
3 | return; |
4 | } |
5 | |
6 | CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; |
7 | CGFloat y = rect.origin.y; |
8 | [UIView beginAnimations:nil context:nil]; |
9 | [UIView setAnimationDuration:0.25]; |
10 | NSArray *subviews = [self subviews]; |
11 | for (UIView *sub in subviews) { |
12 | |
13 | CGFloat maxY = CGRectGetMaxY(sub.frame); |
14 | if (maxY > y - 2) { |
15 | sub.center = CGPointMake(CGRectGetWidth(self.frame)/2.0, sub.center.y - maxY + y - 2); |
16 | } |
17 | } |
18 | [UIView commitAnimations]; |
19 | } |
20 | |
21 | - (void)keyboardShow:(NSNotification *)notif { |
22 | if (self.hidden == YES) { |
23 | return; |
24 | } |
25 | } |
26 | |
27 | - (void)keyboardWillHide:(NSNotification *)notif { |
28 | if (self.hidden == YES) { |
29 | return; |
30 | } |
31 | [UIView beginAnimations:nil context:nil]; |
32 | [UIView setAnimationDuration:0.25]; |
33 | NSArray *subviews = [self subviews]; |
34 | for (UIView *sub in subviews) { |
35 | if (sub.center.y < CGRectGetHeight(self.frame)/2.0) { |
36 | sub.center = CGPointMake(CGRectGetWidth(self.frame)/2.0, CGRectGetHeight(self.frame)/2.0); |
37 | } |
38 | } |
39 | [UIView commitAnimations]; |
40 | } |
41 | |
42 | - (void)keyboardHide:(NSNotification *)notif { |
43 | if (self.hidden == YES) { |
44 | return; |
45 | } |
46 | } |