遇到键盘的时候,很多都是要隐藏键盘这里有几种方法
1、点击空白 是键盘隐藏
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//隐藏键盘
[_text_daikuanzonge resignFirstResponder];
}
这种实现很简单,就是让当前的接受者放弃第一接受者 当然,对于这个方法来讲,我们可以实现很多其他的东西,而不仅仅局限与让键盘隐藏;
2、在键盘上添加一个隐藏按钮
//定义一个toolBar
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
//设置style
[topView setBarStyle:UIBarStyleBlack];
//定义两个flexibleSpace的button,放在toolBar上,这样完成按钮就会在最右边
UIBarButtonItem * button1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * button2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
//定义完成按钮
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)];
//在toolBar上加上这些按钮
NSArray * buttonsArray = [NSArray arrayWithObjects:button1,button2,doneButton,nil];
[topView setItems:buttonsArray];
[textView setInputAccessoryView:topView];
//隐藏键盘
- (void)resignKeyboard {
[textView resignFirstResponder];
}
最终效果
3、把回车键改为隐藏键盘键 这个的前提是不需要用到回车键
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"])
{
[textView resignFirstResponder]; return NO;
}
return YES;
}
当然,我们在开发过程中还有很多的时候由于布局的局限性,键盘出现的时候会把我们需要输入的文本框遮挡住,这个时候就需要把文本框上移就像我们发短信的时候,自动上移
①、在viewWillAppear中添加键盘监听事件
//添加键盘的监听事件
//注册通知,监听键盘弹出事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
//注册通知,监听键盘消失事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardDidHideNotification object:nil];
②、完成①selector中键盘弹出keyboardDidShow:和消失keyboardDidHidden方法
在.m文件#import后面添加
//动画时间
#define kAnimationDuration 0.2
//view高度
#define kViewHeight 56
③、键盘出现
// 键盘弹出时
-(void)keyboardDidShow:(NSNotification *)notification
{
//获取键盘高度
NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect;
[keyboardObject getValue:&keyboardRect];
//调整放置有textView的view的位置
//设置动画
[UIView beginAnimations:nil context:nil];
//定义动画时间
[UIView setAnimationDuration:kAnimationDuration];
//设置view的frame,往上平移
[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, self.view.frame.size.height-keyboardRect.size.height-kViewHeight, 320, kViewHeight)];
[UIView commitAnimations];
}
④、键盘消失
//键盘消失时
-(void)keyboardDidHidden
{
//定义动画
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kAnimationDuration];
//设置view的frame,往下平移
[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, self.view.frame.size.height-kViewHeight, 320, kViewHeight)];
[UIView commitAnimations];
}