思路如下:
在viewcontrol的view下 添加一个scrollview
添加tap手势到scrollview,实现tap隐藏键盘
添加textfiled到scrollview
添加textfiled代理到viewcontroller的代码,实现代理
再editing时 计算textfield对于scrollview的相对高度
增加scrollview的content,相对frame,设置offset
完成推动文本框向上移动,多个文本框时,只针对同一个文本框做参照,防止多次推动影响体验。
这样,在return或tap scrollview时,收起键盘,并且弹出键盘时,又可以拖拽scrollview滚动。
部分代码:
//接口的代理
@interface LoginViewController : UIViewController<UserGuideViewDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate>
// viewdidload中注册Tap手势,和文本框的代理
UITapGestureRecognizer *t = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
t.delegate=self;
[scrollView addGestureRecognizer:t];
txtName.delegate=self;
txtPass.delegate=self;
//处理遮挡的方法
#pragma mark ------处理键盘遮挡------
-(void)singleTap:(UITapGestureRecognizer *) tap {
// 发送resignFirstResponder.
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
//开始动画
[UIView beginAnimations:nil context:nil];
//设定动画持续时间
[UIView setAnimationDuration:0.3];
scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
scrollView.contentSize = CGSizeMake(SCREEN_WIDTH,SCREEN_HEIGHT);
scrollView.scrollEnabled=true;
//动画结束
[UIView commitAnimations];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(scrollView.contentOffset.y>0)
return;
//scrollView.contentSize = CGSizeMake(SCREEN_WIDTH,SCREEN_HEIGHT);;
scrollView.contentSize = CGSizeMake(SCREEN_WIDTH,SCREEN_HEIGHT +216);//原始滑动距离增加键盘高度
scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//把当前的textField的坐标映射到scrollview上
CGPoint pt = [txtName convertPoint:CGPointMake(0, 0) toView:scrollView];
//判断最上面不要去滚动
if(scrollView.contentOffset.y-pt.y+90<=0)
[scrollView setContentOffset:CGPointMake(0, scrollView.contentOffset.y+pt.y-90) animated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField*)theTextField
{
[theTextField resignFirstResponder];
//开始动画
[UIView beginAnimations:nil context:nil];
//设定动画持续时间
[UIView setAnimationDuration:0.3];
scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
scrollView.contentSize = CGSizeMake(SCREEN_WIDTH,SCREEN_HEIGHT);
//动画结束
[UIView commitAnimations];
return YES;
}