隐藏键盘的几种方法

Talk is cheap, show you the code

点击空白处,键盘收回

1
2
3
4
5
6
7
-(void)coClick {
[self.view endEditing:YES];
}
UIControl *co = [[UIControl alloc]initWithFrame:CGRectMake(0,64,ScreenWidth,ScreenHeight)];
[co addTarget:self action:@selector(coClick) forControlEvents:UIControlEventTouchUpInside];
[_tableView addSubview:co];
[_tableView sendSubviewToBack:co];

通知监听键盘

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
//监听键盘弹出

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

//监听键盘隐藏

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

//键盘显示监听方法

- (void)keyboardWillShow:(NSNotification *)noti {

if (IS_IPHONE_4_SCREEN || IS_IPHONE_5_SCREEN) {

[UIView animateWithDuration:0.25 animations:^{

self.view.transform = CGAffineTransformMakeTranslation(0, -100.0);

} completion:^(BOOL finished) {

}];

}

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];

//设置成NO表示当前控件响应后会传播到其他控件上,默认为YES。

tapGestureRecognizer.cancelsTouchesInView = NO;

//将触摸事件添加到当前view

[self.view addGestureRecognizer:tapGestureRecognizer];

}

//键盘隐藏监听方法

- (void)keyboardWillHide:(NSNotification *)noti {

if (IS_IPHONE_4_SCREEN || IS_IPHONE_5_SCREEN) {

[UIView animateWithDuration:0.25 animations:^{

self.view.transform = CGAffineTransformIdentity;

} completion:^(BOOL finished) {

}];

}

}

textField 点击return按键,键盘收回

前提要遵守协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (BOOL)textFieldShouldReturn:(UITextField *)textField {

//回收键盘,取消第一响应者

[textField resignFirstResponder];

[UIView animateWithDuration:0.25 animations:^{

_tableView.frame = CGRectMake(0, 0, YJScreenWidth, YJScreenHeight);

}];

return YES;

}

textView点击return按键,键盘收回

1
2
3
4
5
6
7
8
9
10
11
12
13
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

if([text isEqualToString:@"\n"]) {

[textView resignFirstResponder];

return NO;

}

return YES;

}