一招解决全局键盘遮挡输入框问题

来源:互联网 发布:运动装 休闲装 知乎 编辑:程序博客网 时间:2024/05/16 01:15

原文地址: http://blog.csdn.net/l_nn

解决键盘遮挡问题是通过,监听键盘弹出是对比输入框位置和键盘高度是否存在重叠,已判断是否需要页面上提。。。

此方法是通过在BaseViewController里面添加一个临时的textfield(此后统称为TF),其后在监听试把需要实现的textfiled指向TF已实现全局监听。。

上代码

BaseViewController.m

@interface BaseViewController () {    UITextField *tempTextFiled;    int changeHeight;}@end@implementation BaseViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    //增加监听    [self addNotification];}- (void)addNotification {    //增加监听,当键盘出现或改变时收出消息    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWillShow:)                                                 name:UIKeyboardWillShowNotification                                               object:nil];    //增加监听,当键退出时收出消息    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWillHide:)                                                 name:UIKeyboardWillHideNotification                                               object:nil];}- (void)textFieldDidBeginEditing:(UITextField *)textField {    tempTextFiled = textField;}- (void)textFieldDidEndEditing:(UITextField *)textField {}//当键盘出现时调用- (void)keyboardWillShow:(NSNotification *)aNotification {    NSDictionary * info = [aNotification userInfo];    NSValue *avalue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];    CGRect keyboardRect = [self.view convertRect:[avalue CGRectValue] fromView:nil];    double keyboardHeight = keyboardRect.size.height;//键盘的高度    CGRect frame = [tempTextFiled convertRect:tempTextFiled.frame toView:self.view];    int offset = frame.origin.y + frame.size.height - (RectHeight(self.view) - keyboardHeight);//计算偏移量    if (offset > 0) {        changeHeight = offset+20;        const float movementDuration = 0.3f;        int movement = -changeHeight;        [UIView beginAnimations:@"anim" context:nil];        [UIView setAnimationBeginsFromCurrentState:YES];        [UIView setAnimationDuration:movementDuration];        self.view.frame = CGRectOffset(self.view.frame, 0, movement);        [UIView commitAnimations];    } else {        changeHeight = 0;    }}//当键盘消失时调用- (void)keyboardWillHide:(NSNotification *)aNotification {    const float movementDuration = 0.3f;    int movement = changeHeight;    [UIView beginAnimations:@"anim" context:nil];    [UIView setAnimationBeginsFromCurrentState:YES];    [UIView setAnimationDuration:movementDuration];    self.view.frame = CGRectOffset(self.view.frame, 0, movement);    [UIView commitAnimations];}

注:这样以后继承于BaseViewController的控制器里的所有textfield只需实现delegate=self即可解决遮挡问题

0 0
原创粉丝点击