您的位置:首页 > 移动开发 > IOS开发

[iOS]监控手机虚拟键盘弹出,消失的通知简单使用

2016-01-23 19:07 555 查看
项目中很多时候会遇到弹出的虚拟键盘,遮挡了输入框,或是其他的一些视图,这时候就需要根据键盘的弹出和消失调整视图的坐标,最好的方法就是用系统的通知机制来监控键盘的弹出和消失;

这主要用到了下面的两个通知:

UIKeyboardWillShowNotification//键盘弹出的通知
UIKeyboardWillHideNotification//键盘消失的通知


具体用法如下:在viewDidload方法里注册这两个通知:

//注册监控键盘弹出.隐藏的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:)name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHidden:)name:UIKeyboardWillHideNotification object:nil];


然后实现他的方法,记得方法要带参数,我们需要从参数中获取键盘的一些信息:

- (void) keyBoardWillShow:(NSNotification*) notification
{

NSDictionary *userInfo = [notification userInfo];

//获取键盘的高度
NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

//获取键盘弹出的动画时间
CGFloat interval = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

CGRect keyboardEndFrame = [aValue CGRectValue];
CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil];
CGFloat keyboardHeight = keyboardFrame.size.height;

[UIView animateWithDuration:interval animations:^{
backgroundView.frame = CGRectMake(0,-keyboardHeight/3.0, SCREEN_WIDTH, SCREEN_HEIGHT);
}];
}
-(void)keyBoardWillHidden:(NSNotification*) notification
{
NSDictionary *userInfo = [notification userInfo];
CGFloat interval = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];
[UIView animateWithDuration:interval animations:^{
backgroundView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}];
}


这样我们可以根据获取到的信息,进行一些操作,上面我是做了一个视图上移的动画!!!

对此,我做了一个简单的封装,可一句代码实现监听,含回调处理时间,完整demo下载地址:https://github.com/LQQZYY/KeyboardShowDismissDemo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: