天天看点

ios 解决键盘挡住UITextField的问题

在IOS开发中,如果输入框的位置偏下,那么当键盘弹出时,键盘有可能被挡住

在网上看了很多种方法怎么实现,终于发现一种最为简单的方法

1.在当前Controller中实现UITextField的Delegate

@interface ItemDetailViewController()<UITextFieldDelegate>
           

2.为有可能被遮住的UITextField 设置Delegate 和Tag

[textField3 setDelegate:self];
    [textField3 setTag:3];
           

3.实现UITextFieldDelegate中得协议方法

- (void)textFieldDidBeginEditing:(UITextField *)textField{   //开始编辑时,整体上移
    if (textField.tag==3) {
        [self moveView:-240];//自己需要计算偏移值
    }
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{     //结束编辑时,整体下移
    if (textField.tag==3)
    {
        [self moveView:240];
    }
}
           

4.实现方法moveView

-(void)moveView:(float)move{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    frame.origin.y +=move;//view的y轴上移
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];//设置调整界面的动画效果
}
           

以上就解决了键盘挡住输入框的问题,但是如果界面上有ScrollView,当键盘弹出时,scrollview没办法滑动到界面的顶部

有更完美的解决方法吗,持续研究中