键盘挡住view时,view上移

作者: 崔又淇 | 来源:发表于2018-01-15 23:12 被阅读12次

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

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);

    }];

}

相关文章

网友评论

    本文标题:键盘挡住view时,view上移

    本文链接:https://www.haomeiwen.com/subject/fmdjoxtx.html