版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JennyHermes/article/details/77185117
导读:UITextField(输入框)获取焦点后会弹出键盘,有时候键盘会遮挡住输入框,影响用户交互,所以需要在弹出键盘的时候将视图上移至不会遮挡的位置。下面主要讲述几种常见解决方法。
一、弹出键盘时,将整个视图上移:监听键盘事件
//监听键盘
//1、键盘弹出时
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow) name:UIKeyboardWillShowNotification object:nil];
//2、键盘收回时
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillhide) name:UIKeyboardWillHideNotification object:nil];
/**
监听键盘弹出,输入框上移
*/
-(void)keyboardWillShow{
NSDictionary *userInfo = note.userInfo;
CGFloat duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
CGRect keyFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];//获取键盘高度
CGFloat moveY = keyFrame.origin.y - self.view.frame.size.height-64;
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, moveY);
}];
}
/**
监听键盘弹收回,输入框下移
*/
-(void)keyboardWillhide {
//设置view的frame,往下平移
}
如果你的UIViewController继承UITableViewController,这样系统会自动处理键盘遮挡的问题,如果不是,但又需要使用UITableview,该怎么做呢?
二、如果UITextField放在UITableview上,就要知道每个输入框所在的cell的位置,然后再做处理。
- (void)textFieldDidBeginEditing:(UITextField *)textField {
//获取cell的位置
UITableViewCell *cell = (UITableViewCell *)[textField superview];
NSIndexPath *indexPath = [_publishTableView indexPathForCell:cell];
CGRect rectInTableView = [self.publishTableView rectForRowAtIndexPath:indexPath];
}
CGFloat keyboardHeight = 216.0f;
if (tableview.frame.size.height - keyboardHeight <= rectInTableView.origin.y + textField.frame.size.height+THfloat(36)) {
CGFloat y = rectInTableView.origin.y + textField.frame.size.height+THfloat(36) - (self.publishTableView.frame.size.height - keyboardHeight-THfloat(44));
[UIView beginAnimations:@"srcollView" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.275f];
tableview.frame = CGRectMake(0, -y, THScreenW, THScreenH-64);
[UIView commitAnimations];
}
三、三句代码实现该功能
UITableViewController *tvc = [[UITableViewController alloc]initWithStyle:UITableViewStylePlain];
tableView = tvc.tableView;
[self addChildViewController:tvc];