iOS解决键盘遮挡输入框问题

导读: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];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值