[操作系统]处理UIScrollView中的编辑框被弹出键盘遮挡的问题

当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];
    }
    效果图如下:
    弹出前:
    这里写图片描述
    弹出后:
    这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值