iOS程序猿iOS Developer

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

2016-10-18  本文已影响99人  无意惹东风

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

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的代码

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

上一篇下一篇

猜你喜欢

热点阅读