输入框被键盘遮住了???

当输入框在页面下方时,点击通常会出现被键盘遮挡的现象,那么,怎么去解决呢?针对这一问题,我给出自己的解决方法,具体如下:

1、遵守协议,设置代理:UITextFieldDelegate

UITextField *textField = [[UITextField alloc] init];
textField.delegate = self;

2、实现代理方法- (void)textFieldDidBeginEditing:(UITextField *)textField,调整view的frame:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self changeViewFrameWithTextField:textField];
}

- (void)changeViewFrameWithTextField:(UITextField *)textField
{
    // 获取当前被点击的textfield的frame
    CGRect frame = textField.frame;
    
    // 计算偏移量offset
    // 该偏移量为: 当前textfield的y值 + 当前textfield的高度 - (屏幕的高度 - 键盘的高度 - 键盘toolBar的高度)
    int offset = frame.origin.y + frame.size.height - (ScreenHeight - 216 - 35);
    
    // 设置键盘移动时间
    NSTimeInterval animationDuration = 0.30f;
    
    // 创建执行动画
    [UIView beginAnimations:@"changeKeyboard" context:nil];
    
    [UIView setAnimationDuration:animationDuration];
    
    if(offset > 0)// 当偏移量大于0时,也就是键盘被遮挡时,改变页面的frame
    {
        self.view.frame = CGRectMake(0.0f, -offset ,ScreenHeight ,ScreenHeight);
    }
    
    // 开始动画
    [UIView commitAnimations];
    
}

3、输入结束后,恢复frame的值

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self hidenTextField];
    [self.view resignFirstResponder];
    
    NSTimeInterval animationDuration = 0.30f;
    
    [UIView beginAnimations:@"changeKeyboard" context:nil];
    
    [UIView setAnimationDuration:animationDuration];
    
    self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    
    [UIView commitAnimations];
}

4、如果在键盘return键也有操作时,也要记得写恢复frame的代码

希望可以对大家有所帮助。康撒米哒~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容