ios 处理键盘遮挡问题

项目中经常会用到输入框,难免会碰到键盘遮挡其他控件的问题 那么如何解决 键盘遮挡的问题呢?

首先这是我的项目中的界面图

这里写图片描述

然后我们点击下面的详细地址或者输入验证码

这里写图片描述

我们发现键盘遮蔽住了下面的输入框 接下来说解决方案

第一步

 tfDetailAddress.delegate=self;
  tfVerCode.delegate=self;

第二步 在输入框开始编辑的时候添加观察者

-(void)textFieldDidBeginEditing:(UITextField *)textField{


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

}
#pragma mark 键盘操作
- (void)keyboardWillChange:(NSNotification *)note
{

    NSDictionary *userInfo = note.userInfo;
    CGFloat duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];

    CGRect keyFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    //这个64是的navigationbar加上状态栏20的高度,可以看自己的实际情况决定是否减去;
    CGFloat moveY = keyFrame.origin.y - self.view.frame.size.height+64;

    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, moveY);
    }];

}

第三步 在viewdidLoad里 添加隐藏键盘的观察者


[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
隐藏键盘
- (void)keyboardWillHide:(NSNotification *)nsnotification
{

    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];

    [UIView animateWithDuration:0.2 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

然后运行

这里写图片描述

我们发现键盘成功弹上去了 然后按键盘上的回收三角形

这里写图片描述

**发现没有任何问题 在这里补充一个问题 就是 当我们正在编辑的时候 如果切换出去的话,然后再次切回来程序 发现键盘没有回收,这个时候点击回收三角形进行回收会出现如下问题
整个视图往下移了
**

这里写图片描述

解决方法就是后台切入前台的时候 把 editing置为yes就可以了

在 viewdidload里添加如下代码

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground)name:UIApplicationWillEnterForegroundNotification object:nil];
对应的函数
- (void)applicationWillEnterForeground{
    [self.view endEditing:YES];
}

这样就ok了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值