几种常用的隐藏键盘的方法

话不多说,直接上代码:

1、//点击空白处,键盘收回

UIControl *co = [[UIControl alloc]initWithFrame:CGRectMake(0,64,ScreenWidth,ScreenHeight)];

[co addTarget:self action:@selector(coClick) forControlEvents:UIControlEventTouchUpInside];

[_tableView addSubview:co];

[_tableView sendSubviewToBack:co];

-(void)coClick{

[self.view endEditing:YES];

}

2、通知监听键盘

//监听键盘弹出

[[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) {

}];

}

}

3、textField 点击return按键,键盘收回(前提要遵守协议)

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

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

[textField resignFirstResponder];

[UIView animateWithDuration:0.25 animations:^{

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

}];

return YES;

}

4、textView点击return按键,键盘收回

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

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

[textView resignFirstResponder];

return NO;

}

return YES;

}

手上没活,突然间想总结一下啦,希望对大家有所帮助。欢迎入群,一起探讨QQ群:333261719

你可能感兴趣的:(几种常用的隐藏键盘的方法)