// 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;
}