iOS uitextFiled输入框被软键盘遮盖怎么办

来源:互联网 发布:公务员培训老师知乎 编辑:程序博客网 时间:2024/05/17 05:51

一般我们在tableView或者scrollView里放好几个textFiled的时候,下面的textFiled会被弹出来的软键盘遮盖,这是在所难免的。这里介绍一下苹果官方给出的解决方法:

首先注册观察者监听UIKeyBoardWillShow和WillHide事件;

-(void)viewWillAppear:(BOOL)animated

{

    [superviewWillAppear:animated];

    

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];

}


实现自定义方法:

-(void)keyboardWillShow:(NSNotification*)noti

{

    //键盘输入的界面调整

    

    NSDictionary *userInfo = [notiuserInfo];

    CGRect keyboardRect = [[userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    NSTimeInterval animationDuration = [[userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];

    CGRect newFrame =self.view.frame;

    newFrame.size.height -= keyboardRect.size.height;

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

    [UIViewsetAnimationDuration:animationDuration];

    self.view.frame = newFrame;

    [UIViewcommitAnimations];

}

-(void)keyboardWillHide:(NSNotification *)noti

{

    NSDictionary *userInfo = [notiuserInfo];

    CGRect keyboardRect = [[userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    NSTimeInterval animationDuration = [[userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];

    CGRect newFrame =self.view.frame;

    newFrame.size.height += keyboardRect.size.height;

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

    [UIViewsetAnimationDuration:animationDuration];

    self.view.frame = newFrame;

    [UIViewcommitAnimations];

}


最后移除观察者:

-(void)viewWillDisappear:(BOOL)animated

{

    [superviewWillDisappear:animated];

    

    [[NSNotificationCenterdefaultCenter] removeObserver:selfname:UIKeyboardWillHideNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter] removeObserver:selfname:UIKeyboardWillShowNotificationobject:nil];

}


0 0
原创粉丝点击