前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS 监听键盘

iOS 监听键盘

原创
作者头像
用户7108768
修改2021-10-29 11:52:43
1.5K0
修改2021-10-29 11:52:43
举报

百度所查到的键盘监听大部分用的是

UIKeyboardDidShowNotification//已经显示

UIKeyboardDidHideNotification//已经隐藏

然后我自己去试一直觉得一些空间跟随键盘的移动是有时间间隔的  一直想不明白他们是怎么实现的  求大神告知  所以自己看源码发现还有

UIKeyboardWillShowNotification//将要显示

UIKeyboardDidHideNotification//将要隐藏

这样是能完美的解决问题的  至少在我自己的项目需求中是可以的

最后别忘记在控制器消失中移除观察者哦

- (void) registerForKeyboardNotifications{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];

}

//键盘显示注册通知

- (void) keyboardWasShown:(NSNotification *) note{

// 获取位置和大小

CGRect keyboardBounds;

    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];

NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];

// 获取位置和大小

CGRect containerFrame = _menuView.frame;

// 计算出y坐标

    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);

_mnueHeight = containerFrame.origin.y;

_maxHeight = containerFrame.origin.y;

// 动画改变位置

    [UIView animateWithDuration:[duration doubleValue] animations:^{

        [UIView setAnimationBeginsFromCurrentState:YES];

        [UIView setAnimationDuration:0.1];

        [UIView setAnimationCurve:[curve intValue]];

// 更改位置

_menuView.frame = containerFrame;

    }];

}

//键盘消失通知

- (void) keyboardWasHidden:(NSNotification *) note{

NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

// 获取位置和大小

CGRect containerFrame = _menuView.frame;

    containerFrame.origin.y = self.view.bounds.size.height - containerFrame.size.height;

// 动画改变位置

    [UIView animateWithDuration:[duration doubleValue] animations:^{

        [UIView setAnimationBeginsFromCurrentState:YES];

        [UIView setAnimationDuration:[duration doubleValue]];

        [UIView setAnimationCurve:[curve intValue]];

// 更改位置

_menuView.frame = containerFrame;

    }];

}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档