自定义键盘上方工具栏随键盘一起运动的问题

监听键盘变化的通知。有改变的,显示的,隐藏的几个系统通知。

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification  object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification  object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

这么处理,感觉跟随键盘一起走比较自然一些。显示和隐藏的通知记录状态,改变的通知去改变尺寸做动画,(暂时这么处理的,可能有更好的解决方案,还没发现)

#pragma mark *************** 键盘通知 ***************
-(void)keyboardWillChange:(NSNotification *)note {

    NSDictionary *userInfo = note.userInfo;
    CGRect keyboardFrame =[userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = keyboardFrame.origin.y;
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    if (duration == 0) {//切换输入法
        self.containerView.mj_y = keyboardY - SCREENHEIGHT;
    }else{
        
        [UIView animateWithDuration:duration delay:0.0 options:7 << 16 animations:^{
            self.containerView.mj_y = keyboardY - SCREENHEIGHT;
            if (self.keyboardView.alpha == 0) {
                [self.chatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.keyboardView.mas_top).offset(-5);
                }];
            }else{
                [self.chatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.keyboardView.mas_top).offset(-BottomH-5+50);
                }];
            }
            [self.containerView layoutIfNeeded];
        } completion:nil];
    }
}

-(void)keyboardWillShow:(NSNotification *)note {
    self.keyboardView.alpha = 1;
}

- (void)keyboardWillHide:(NSNotification *)note {
    self.keyboardView.alpha = 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容