几种方法隐藏键盘

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

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

[textview resignFirstResponder];

return NO;

}

return YES;

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

[textview resignFirstResponder];

}

-(void)viewWillAppear:(BOOL)animated{

//注册通知,监听键盘弹出事件

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];

//注册通知,监听键盘消失事件

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardDidHideNotification object:nil];

}

// 键盘弹出时

-(void)keyboardDidShow:(NSNotification *)notification

{

//获取键盘高度

NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];

CGRect keyboardRect;

[keyboardObject getValue:&keyboardRect];

//调整放置有textView的view的位置

//设置动画

[UIView beginAnimations:nil context:nil];

//定义动画时间

[UIView setAnimationDuration:5];

//设置view的frame,往上平移

[(UIView *)[self.view  viewWithTag:1000] setFrame:CGRectMake(0, self.view.frame.size.height-keyboardRect.size.height-50, 320, 50)];

[UIView commitAnimations];

}

//键盘消失时

-(void)keyboardDidHidden

{

//定义动画

[UIView beginAnimations:nil context:nil];

[UIView setAnimationDuration:5];

//设置view的frame,往下平移

[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, self.view.frame.size.height-50, 320, 50)];

[UIView commitAnimations];

}

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