iOS 根据弹出的键盘高度改变控件Frame

根据键盘高度改变控件尺寸.gif

键盘高度是不一样的所以不能写死 需要根据弹出的键盘动态获取

第一步

在需要的地方注册监听

    //监听键盘尺寸改变(包含键盘弹出)
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillChangeFrame:)
                                                 name:UIKeyboardWillChangeFrameNotification
                                               object:nil];
/*
     有些地方说这里监听`UIKeyboardWillShowNotification` 但是这个监听仅仅只是监听键盘弹出这一个事件
     如果在键盘弹出期间键盘改变了尺寸是无法监听到的
     比如 弹出的键盘高度是88 你能监听到 然后切换了键盘类型 键盘变成了40高  键盘变成40高这个事件你是无法监听到并且做相应处理的
     个人觉得监听`UIKeyboardWillChangeFrameNotification`会好一些
    */
    
    //监听收回键盘
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHide:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];

第二步

实现监听的方法

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    
   NSDictionary *info = [notification userInfo];
    //获取改变尺寸后的键盘的frame
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    [UIView animateWithDuration:0.2 animations:^{
        
        CGRect frame = _settingTableView.frame;
        //如果是监听键盘尺寸改变 一定要用计算最终高度的方式来计算 如果用控件自加自减的方式会出错
        frame.size.height = SCREEN_HEIGHT - 64 - endKeyboardRect.size.height;
        //这里的计算思路是 屏幕高度  - (导航栏 + 状态栏) - 当前键盘的高度 = tableView的高度 
        //可以根据实际情况做处理
        _settingTableView.frame = frame;
    }];
}


- (void)keyboardDidHide:(NSNotification *)aNotification{
        //键盘收起后恢复控件尺寸
        [UIView animateWithDuration:0.2 animations:^{
            
            CGRect frame = _scrollView.frame;
            //同理这里也应该是计算最终高度的方式来计算
            frame.size.height = SCREEN_HEIGHT - 64;
            _scrollView.frame = frame;
        } completion:^(BOOL finished) {
            
        }];
}

你可能感兴趣的:(iOS 根据弹出的键盘高度改变控件Frame)