键盘状态监听

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#import "RootViewController.h"

@interface RootViewController ()<UITextFieldDelegate>

@end

@implementation RootViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
myView.backgroundColor = [UIColor blackColor];
[self.view addSubview:myView];


[self.view setBackgroundColor:[UIColor redColor]];

[self createTextField];
}
-(void)createTextField{
// 初始化UITextField并设置frame
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 400, 100, 50)];
// 设置背景色
textField.backgroundColor = [UIColor yellowColor];

textField.delegate = self;

// 添加到视图
[self.view addSubview:textField];


// 键盘状态改变的时候,会发出以下通知
// UIKeyboardWillShowNotification; 键盘即将显示
// UIKeyboardDidShowNotification; 键盘显示完毕
// UIKeyboardWillHideNotification; 键盘即将消失
// UIKeyboardDidHideNotification;键盘消失完毕
// UIKeyboardWillChangeFrameNotification 键盘即将改变frame
// UIKeyboardDidChangeFrameNotification 键盘已经改变frame

// 获取通知中心
NSNotificationCenter*center = [NSNotificationCenter defaultCenter];

// 监听键盘弹出通知
[center addObserver:self selector:@selector(KeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
// 监听键盘收起通知
[center addObserver:self selector:@selector(KeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

// 成为第一响应者
// [textField becomeFirstResponder];
}

//键盘将要消失时
-(void)KeyboardWillHide:(NSNotification*)noti{
NSLog(@"%@",noti.userInfo);
// UIKeyboardAnimationDurationUserInfoKey = "0.25";
// UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
// UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
// UIKeyboardFrameEndUserInfoKey = "NSRect: {{0,667}, {375, 258}}";


self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}
//键盘将要出现
-(void)KeyboardWillShow:(NSNotification*)noti{
NSLog(@"%@",noti.userInfo);
// UIKeyboardAnimationDurationUserInfoKey = "0.25";
// UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
// UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
// UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
// UIKeyboardIsLocalUserInfoKey = 1;

CGRect rect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
NSLog(@"rect = %@",NSStringFromCGRect(rect));


self.view.frame = CGRectMake(0, -rect.size.height, self.view.frame.size.width, self.view.frame.size.height);
}

#pragma mark - textField delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
// 取消第一响应者
[textField resignFirstResponder];
return YES;
}
@end