`
woodn_z
  • 浏览: 44272 次
  • 性别: Icon_minigender_1
  • 来自: 无锡
文章分类
社区版块
存档分类
最新评论

iphone 键盘遮盖TextField的解决方法

阅读更多
常常我们在做界面的时候会用到文本框输入,但当把输入文本框放的过于低,就会导致在填写信息的时候弹出的虚拟键盘遮盖输入文本框,导致看不见所输入的信息,这对于用户体验当然很不好,所以我们需要改进这一情况,方法大致就是在点击输入文本框准备输入的时候,使得文本框上移到用户能看见的地方。这方法是网上资料,或许还有别的更好的解决方法,希望大家都能发出来。

比如如下的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];
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics