ios 处理键盘遮挡问题

来源:互联网 发布:mac修改hosts文件翻墙 编辑:程序博客网 时间:2024/04/17 06:29

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

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

这里写图片描述

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

这里写图片描述

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

第一步

 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了

原创粉丝点击