iOS键盘遮挡文本框的解决方案

来源:互联网 发布:mac怎么整理照片 编辑:程序博客网 时间:2024/06/10 09:40

在开发过程中我们经常会遇到虚拟键盘遮挡输入框的问题,本人也上网查了一些资料,发现有些兄弟给的解决方案是这样的,他不去管我当前的光标位置只是去把键盘上面的整个UIView向上推了键盘高度,这种方式虽然解决了虚拟键盘遮挡输入框的问题但是对用户不够友好,下面我介绍一种方法来解决该问题:

首先我们要定义一个 UITextField 类型的控件用来存储当前光标所在的 UITextField ,之后我们要监听两个键盘相关的通知  keyboardDidShow 和 keyboardWillBeHidden,直接上代码:

- (void)keyboardDidShow:(NSNotification *)notification {    NSDictionary *info = [notification userInfo];    CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];    kbRect = [self.view convertRect:kbRect fromView:nil];    UIEdgeInsets contentInsets = contentView.contentInset;    contentInsets.bottom = kbRect.size.height;    //    UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);    contentView.contentInset = contentInsets;    contentInsets = contentView.scrollIndicatorInsets;    contentInsets.bottom = kbRect.size.height;    contentView.scrollIndicatorInsets = contentInsets;    CGRect aRect = self.view.frame;    //    CGRect aRect = tableView.frame;    aRect.size.height -= kbRect.size.height;    if (!CGRectContainsPoint(aRect, _activeField.frame.origin)) {        [contentView scrollRectToVisible:_activeField.frame animated:YES];    } else {        NSLog(@"not Contains");    }}
上面的代码用来检测键盘是否需要移动和需要移动的距离,其中的 _activeField 就是我们用来存放光标所属的UItextField,存放的代码应该在 UITextField 的 beginediting的代理中实现的。。

- (void)keyboardWillBeHidden:(NSNotification *)notification {    UIEdgeInsets contentInsets = contentView.contentInset;    contentInsets.bottom = 0;    //    UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);    contentView.contentInset = contentInsets;    contentInsets = contentView.scrollIndicatorInsets;    contentInsets.bottom = 0;    contentView.scrollIndicatorInsets = contentInsets;    //    UIEdgeInsets contentInsets = UIEdgeInsetsZero;    //    scrollView.contentInset = contentInsets;    //    scrollView.scrollIndicatorInsets = contentInsets;    [_activeField resignFirstResponder];}

上述代码实现了退出第一响应者,并让虚拟键盘归位。。


0 0
原创粉丝点击