·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 处理UIScrollView中的编辑框被弹出键盘遮挡的问题

处理UIScrollView中的编辑框被弹出键盘遮挡的问题

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

当UIScrollView中的某一行存在编辑框时,点击编辑框,弹出的键盘有可能遮挡住编辑框,造成体验效果很不好。解决的方法很简单,就是将UIScrollView的内容和UIScrollView容器的内边距(准确来说是底边距)增加正好是键盘高度的距离,ios系统会将选中的行重新定位,位置正好是距离窗口底边相同距离的地方,当然,键盘缩回去的时候注意要把内边距再设置回来。涉及到的最主要的函数就是UIScrollView的setContentInset函数。

首先,要在程序开始的地方注册键盘弹出和缩回的通知监听:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

 

keyboardWillShow和keyboardWillHide的实现如下:

- (void)keyboardWillShow:(NSNotification *)notification
{

  //键盘弹出后的frame
    NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardBounds;
    [keyboardBoundsValue getValue:&keyboardBounds];

    //设置新的内边距,这个内边距是UIScrollView的最后一行距离UIScrollView底边框的距离,

  //这样当该函数触发式,系统会将当前选中行距离窗口底边的距离设为该值,从而正好不被键盘遮盖住。
    UIEdgeInsets e = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
    [[self tableView] setContentInset:e];

 

  //调整滑动条距离窗口底边的距离

    [[self tableView] setScrollIndicatorInsets:e];
}

- (void)keyboardWillHide:(NSNotification *)notification
{

 //键盘缩回后,恢复正常设置
    UIEdgeInsets e = UIEdgeInsetsMake(0, 0, 0, 0);
    [[self tableView] setScrollIndicatorInsets:e];
    [[self tableView] setContentInset:e];
}

效果图如下:

弹出前:

弹出后: