您的位置:首页 > 产品设计 > UI/UE

如何处理键盘遮挡UITextField

2016-04-25 11:37 441 查看
#import "ViewController.h"

@interface
ViewController ()<UITextFieldDelegate>

@property (weak,
nonatomic) IBOutletUITextField *name;

@property (weak,
nonatomic) IBOutletUITextField *password;

@end

@implementation ViewController

- (void)viewDidLoad {

[superviewDidLoad];

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

//指定本身为代理

self.name.delegate =self;

self.password.delegate =self;

//指定编辑时键盘的return键类型

self.name.returnKeyType
= UIReturnKeyNext;

self.password.returnKeyType
= UIReturnKeyDefault;

//注册键盘响应事件方法

[self.nameaddTarget:selfaction:@selector(nextOnKeyboard:)forControlEvents:UIControlEventEditingDidEndOnExit];

[self.passwordaddTarget:selfaction:@selector(nextOnKeyboard:)forControlEvents:UIControlEventEditingDidEndOnExit];

//添加手势,点击屏幕其他区域关闭键盘的操作

UITapGestureRecognizer *gesture = [[UITapGestureRecognizeralloc]
initWithTarget:selfaction:@selector(hidenKeyboard)];

gesture.numberOfTapsRequired =1;

[self.viewaddGestureRecognizer:gesture];

}

- (void)didReceiveMemoryWarning {

[superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

//UITextField的协议方法,当开始编辑时监听

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

NSTimeInterval animationDuration=0.30f;

[UIViewbeginAnimations:@"ResizeForKeyboard"context:nil];

[UIView setAnimationDuration:animationDuration];

float width =
self.view.frame.size.width;

float height =
self.view.frame.size.height;

//上移30个单位,按实际情况设置

CGRect rect=CGRectMake(0.0f,-200,width,height);

self.view.frame=rect;

[UIViewcommitAnimations];

return
YES;

}

//恢复原始视图位置

-(void)resumeView

{

NSTimeInterval animationDuration=0.30f;

[UIViewbeginAnimations:@"ResizeForKeyboard"context:nil];

[UIView setAnimationDuration:animationDuration];

float width =
self.view.frame.size.width;

float height =
self.view.frame.size.height;

//如果当前View是父视图,则Y为20个像素高度,如果当前View为其他View的子视图,则动态调节Y的高度

float Y = 20.0f;

CGRect rect=CGRectMake(0.0f,Y,width,height);

self.view.frame=rect;

[UIViewcommitAnimations];

}

//隐藏键盘的方法

-(void)hidenKeyboard

{

[self.nameresignFirstResponder];

[self.passwordresignFirstResponder];

[selfresumeView];

}

//点击键盘上的Return按钮响应的方法

-(void)nextOnKeyboard:(UITextField *)sender

{

if (sender ==
self.name) {

[self.passwordbecomeFirstResponder];

}else if (sender ==self.password){

[selfhidenKeyboard];

}

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: