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];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容