键盘挡住view时,view上移

添加键盘弹起和收起的监听

1.监听键盘的通知

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];

}

- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];

}


2.textfiled的代理方法,获取点击的是那个view

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

    self.tmpView = (InputView *)textField.superview;

    return YES;

}

3.键盘弹出的方法

- (void)keyBoardDidShow:(NSNotification *)notification {

    CGRect rect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

// 打印结构体的方法

//    NSLog(@"%@", NSStringFromCGRect(rect));

    CGFloat kbHeight = rect.size.height;

    CGFloat offset = (_tmpView.frame.origin.y + _tmpView.frame.size.height + 40 + _backScrollView.frame.origin.y) - (self.view.frame.size.height - kbHeight);

    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    if(offset > 0) {

        [UIView animateWithDuration:duration animations:^{

            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);

        }];

    }

}

4.键盘回收的方法

- (void)keyBoardDidHide:(NSNotification *)notif {

    double duration = [[notif.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    [UIView animateWithDuration:duration animations:^{

        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    }];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容