textfield 弹出键盘输入时上浮代码

屏幕快照 2015-03-27 下午2.49.55.png

在代理方法中,调用这三个方法,主要是为了避免输入状态下直接跳输入框这种输入,所以调用了代理中的三个状态来满足

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSTimeInterval animationDuration = 0.30f;
    self.frame = textframe;
    //self.view移回原位置
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return true;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField;
{
    textframe = self.frame;
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.frame;
    frame.origin.y -=100;
    self.frame = frame;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSTimeInterval animationDuration = 0.30f;
    self.frame = textframe;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView commitAnimations];
    [textField resignFirstResponder];
}



其中需要注意的是 textframe 是一个全局变量,是先存放原来的位置,等后面容易恢复,然后就是我这个实例是在 view 里面实现的,所以用的 self.frame, 如果是在 controller 里面实现的,则需要写成 self.view.frame

当然上面的是通过三个方法实现的,还有的就是可以直接让他自动适应高度来判断,方法是类似的

1.开始输入文本时,一般需要判断键盘是否遮挡住了UITextField 视图,是的话需要调整整个视图的位置。

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    CGRect textFrame =  textField.frame;
    float textY = textFrame.origin.y+textFrame.size.height;
    float bottomY = self.view.frame.size.height-textY;
    if(bottomY<216)  //判断当前的高度是否已经有216,如果超过了就不需要再移动主界面的View高度
    {
        float moveY = 216-bottomY;
        prewMoveY = moveY;
    
        NSTimeInterval animationDuration = 0.30f;
        CGRect frame = self.view.frame;
        frame.origin.y -=moveY;//view的Y轴上移
        frame.size.height +=moveY; //View的高度增加
        self.view.frame = frame;
        [UIView beginAnimations:@"ResizeView" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];//设置调整界面的动画效果
    }
    return YES;
}

2. 输入文本结束时,调回输入前的视图布局

-(void ) textFieldDoneEditing:(id) sender{
	if (sender == _telNum) {
		_payButton.enabled = YES;
        
        NSTimeInterval animationDuration = 0.30f;
        CGRect frame = self.view.frame;
        //还原界面
        frame.origin.y +=prewMoveY;
        frame.size. height -=prewMoveY;
        self.view.frame = frame;
        //self.view移回原位置
        [UIView beginAnimations:@"ResizeView" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];
        [sender resignFirstResponder];
        
	}
}

这两个方法其实是一样的,只是修改了点逻辑而已,用哪个都可以

Last modification:January 1st, 1970 at 08:00 am
如果看了这个文章可以让你少加会班,可以请我喝杯可乐
已打赏名单
微信公众号

Leave a Comment