如果根据键盘的frame始终让一个控件始终在键盘的顶部

我们发现很多时候系统提供的键盘功能有限 有些功能无法实现,所以我们通常的做法就是自定义一个工具条放在键盘的顶部。

那么我们如何知道键盘的frame呢? 这个时候就需要监听键盘发出的通知,在ios中当键盘自身的frame发生改变的时候 它会发出以下通知:

键盘的frame(位置)即将改变, 就会发出UIKeyboardWillChangeFrameNotification 所以我们可以借助这个方法 获取到键盘最终的frame  拿到键盘的高度

如下代码:就监听了键盘的frame 将要改变的通知

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

实现监听方法代码如下:

/**
 * 监听键盘的frame发生改变的通知
 */
- (void)keyboardChangeFrame:(NSNotification*)note
{
    //拿到键盘最终的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //拿到键盘弹出的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
       
        self.toolBar.transform = CGAffineTransformMakeTranslation(0, frame.origin.y - ScreenH );
        
    }];
    
}

还有另外一种方法也可以达到同样的效果,那就是监听键盘的弹出和隐藏

如下代码时间了监听监听的弹出和隐藏的通知:

    // 键盘即将弹出, 就会发出UIKeyboardWillShowNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    // 键盘即将隐藏, 就会发出UIKeyboardWillHideNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

具体的监听方法实现代码如下:

/**
 * 监听键盘即将显示的通知
 */
- (void)keyboardWillShow:(NSNotification*)noto
{
    //获取键盘弹出的时间
    CGFloat duration = [noto.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //取出键盘的高度
    CGRect keyboardF = [noto.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardH = keyboardF.size.height;
    
    //执行动画跳转工具栏条的Y值
    [UIView animateWithDuration:duration animations:^{
        self.toolBar.transform = CGAffineTransformMakeTranslation(0, -keyboardH);
    }];
    
}
/**
 * 监听键盘即将隐藏的通知
 */
- (void)keyboardWillHide:(NSNotification*)noto
{
    //获取键盘弹出的时间
    CGFloat duration = [noto.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //让工具条的transform复位
    [UIView animateWithDuration:duration animations:^{
        self.toolBar.transform = CGAffineTransformIdentity;
    }];
    
}

自己实现的新浪微博的发布微博界面如下:

原文地址:https://www.cnblogs.com/syios/p/4781351.html