ios 键盘遮盖TextField的解决方法

来源:互联网 发布:淘宝在线转换工具 编辑:程序博客网 时间:2024/05/21 09:52
常常我们在做界面的时候会用到文本框输入,但当把输入文本框放的过于低,就会导致在填写信息的时候弹出的虚拟键盘遮盖输入文本框,导致看不见所输入的信息,这对于用户体验当然很不好,所以我们需要改进这一情况,方法大致就是在点击输入文本框准备输入的时候,使得文本框上移到用户能看见的地方。这方法是网上资料,或许还有别的更好的解决方法,希望大家都能发出来。 

比如如下的UIViewController有一个UITextField对象

@interface MyViewController : UIViewController <UITextFieldDelegate>{    UITextField *textField;}

记住这里要加上<UITextFieldDelegate>,使得UITextField对象能用代理方法 

当然在viewDidLoad方法中,要设置 textField.delegate = self;这样就能找到自己的代理方法实现 

如下的代理方法:

//该方法为点击输入文本框要开始输入是调用的代理方法:就是把view上移到能看见文本框的地方- (void)textFieldDidBeginEditing:(UITextField *)textField{    CGFloat keyboardHeight = 216.0f;    if (self.view.frame.size.height - keyboardHeight <= textField.frame.origin.y + textField.frame.size.height) {        CGFloat y = textField.frame.origin.y - (self.view.frame.size.height - keyboardHeight - textField.frame.size.height - 5);        [UIView beginAnimations:@"srcollView" context:nil];        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];        [UIView setAnimationDuration:0.275f];         self.view.frame = CGRectMake(self.view.frame.origin.x, -y, self.view.frame.size.width, self.view.frame.size.height);        [UIView commitAnimations];    }}//该方法为点击虚拟键盘Return,要调用的代理方法:隐藏虚拟键盘- (BOOL)textFieldShouldReturn:(UITextField *)textField{    [textField resignFirstResponder];    return YES;}//该方法为完成输入后要调用的代理方法:虚拟键盘隐藏后,要恢复到之前的文本框地方- (void)textFieldDidEndEditing:(UITextField *)textField{    [UIView beginAnimations:@"srcollView" context:nil];    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];    [UIView setAnimationDuration:0.275f];    self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);    [UIView commitAnimations];}

上面方法中键盘高度使用了固定值216.0f,但是由于iphone机型不同,导致高度不同,所以不能简单采取固定值的方式,可以动态获取键盘的高度,然后设置该值。

    //注册键盘出现的通知,为了动态获取键盘高度    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];    [defaultCenter addObserver:self                      selector:@selector(keyboardWillShow:)                          name:UIKeyboardWillShowNotification                        object:nil];

/** *  键盘出现触发的事件 * *  @param aNotification <#aNotification description#> */- (void)keyboardWillShow:(NSNotification *)aNotification {    //获取键盘的高度    NSDictionary *userInfo = [aNotification userInfo];    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];    CGRect keyboardRect = [aValue CGRectValue];    keyboardHight = keyboardRect.size.width;}

参考:http://woodn-z.iteye.com/blog/1167652

0 0
原创粉丝点击