iOS 监听键盘伸缩调整输入框位置

1、监听键盘弹出或收回通知

监听键盘弹出和收回还可以用这两个通知:UIKeyboardWillShowNotification(弹出)和UIKeyboardWillHideNotification(收回),但这样的话就需要监听两个通知,太麻烦!所以这里只监听UIKeyboardWillChangeFrameNotification(键盘的frame改变时就会收到这个通知,包括弹出和收回)通知。代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];

    //监听键盘弹出或收回通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

2、收到键盘frame改变通知时的操作

//实现接收到通知时的操作
-(void) keyBoardChange:(NSNotification *)note
{
    //获取键盘弹出或收回时frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //获取键盘弹出所需时长
    float duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //添加弹出动画
    [UIView animateWithDuration:duration animations:^{
        self.chatToolBar.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.origin.y - self.view.frame.size.height);
    }];
}

在transform时,自己老是算不清楚在y方向的形变量,在这里当自己做个笔记,如果能帮助到你更好!记住:keyboardFrame.origin.y - self.view.frame.size.height

3、移除通知

//控制器销毁移除通知
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

推荐阅读更多精彩内容