UITextField被键盘挡住的解决办法

// 1.初始化

#import "FIrstViewController.h"


@interface FIrstViewController ()<UITextFieldDelegate>


@property(nonatomic,assign)float prewMoveY;

@property(nonatomic,strong)UIScrollView * scroll;

@end


static int prewTag = -1 ;

@implementation FIrstViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,64,KViewWidth,KViewHeigth-64)];

    _scroll.backgroundColor = [UIColor lightGrayColor];

    [self.view addSubview:_scroll];

    [self initView];

}

// 2.初始化UITextField

- (void) initView

{

    for ( int i = 0; i< 3; i++) {

        UITextField * tf = [[UITextField alloc] initWithFrame:CGRectMake(100, 350+50*i,200, 30)];

        tf.placeholder = [NSString stringWithFormat:@"请输入%d",i];

        tf.tag = 200 + i;

        tf.delegate = self;

        tf.clearsOnBeginEditing = YES;// 再次编辑 就清空

        tf.borderStyle = UITextBorderStyleRoundedRect;

        [_scroll addSubview:tf];

    }

}

// 3. 开始编辑的时候 如果被挡住了 _scroll 向上移动

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    CGRect textFrame = textField.frame;

    float textY = textFrame.origin.y + textFrame.size.height;

    float buttomY = _scroll.frame.size.height - textY;// 距离_scroll 底部的距离

    if (buttomY > 216) {

        prewTag = -1;

        return  YES;

    }

    if (buttomY < 216) {

        prewTag  =  textField.tag;

        float MoveY = 216 - buttomY +64; // 

        _prewMoveY = MoveY;

        _scroll.frame = CGRectMake(0,64-MoveY,self.view.frame.size.width,self.view.frame.size.height-64);

       NSLog(@"改变:%f",_scroll.frame.size.height);

    }

    return YES;

}

// 4.编辑完成 _scroll 恢复到原来的位置

- (void)textFieldDidEndEditing:(UITextField *)textField

{

    if (prewTag == -1) {

        return;

    }

    _scroll.frame = CGRectMake(0,64,self.view.frame.size.width,self.view.frame.size.height - 64);

}

// 5.一个UITextField 编辑完成 点击return键 自动换到下一个UITextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    if (textField.tag == 200) {

        [textField resignFirstResponder];

        UITextField * tf = (UITextField*)[_scroll viewWithTag:201];

        [tf becomeFirstResponder];

    }

    if (textField.tag == 201) {

        [textField resignFirstResponder];

        UITextField * tf = (UITextField*)[_scroll viewWithTag:202];

        [tf becomeFirstResponder];

    }

    if (textField.tag == 202) {

        [textField resignFirstResponder];

        UITextField * tf = (UITextField*)[_scroll viewWithTag:203];

        [tf becomeFirstResponder];

    }

    return YES;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值