键盘通知
由于键盘的通知是系统自动的,因此可以不用创建通知,只需要注册一个监听器监听即可,当收到相应的通知去执行方法。
键盘状态改变的时候,系统会发出一些特定的通知
UIKeyboardWillShowNotification // 键盘即将显示
UIKeyboardDidShowNotification // 键盘显示完毕
UIKeyboardWillHideNotification // 键盘即将隐藏
UIKeyboardDidHideNotification // 键盘隐藏完毕
UIKeyboardWillChangeFrameNotification // 键盘的位置尺寸即将发生改变
UIKeyboardDidChangeFrameNotification // 键盘的位置尺寸改变完毕
系统发出键盘通知时,会附带一下跟键盘有关的额外信息(字典),字典常见的key如下:
UIKeyboardFrameBeginUserInfoKey // 键盘刚开始的frame
UIKeyboardFrameEndUserInfoKey // 键盘最终的frame(动画执行完毕后)
UIKeyboardAnimationDurationUserInfoKey // 键盘动画的时间
UIKeyboardAnimationCurveUserInfoKey // 键盘动画的执行节奏(快慢)
- (void)viewDidLoad {
//监听键盘frame变化的通知,键盘位置发生变化时,让输入框位置也随之变化。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveKeyboardFrameChangeNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)receiveKeyboardFrameChangeNotification:(NSNotification *)noti{
NSLog(@"%@",noti.userInfo);
/*
{
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25";
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 216}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 775}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 775}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 216}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 216}}";
UIKeyboardIsLocalUserInfoKey = 1;
}
*/
//NSValue值类,基本类型和结构体不能直接放入数组和字典中,如果需要把结构体放入数组或字典,那么必须把结构体转换为NSValue,然后把NSValue放入字典或数组。
NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//CGRect rect = [value CGRectValue];
CGRect rect;
[value getValue:&rect];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
//7是键盘动画专用速率
//[noti.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] = 7
[UIView setAnimationCurve:[[noti.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue]];
_inputView.frame = CGRectMake(0, rect.origin.y-40, 375, 40);
_table.frame = CGRectMake(0, 0, 375, _inputView.frame.origin.y);
if (_array.count>1) {
[_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_array.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];
}
[UIView commitAnimations];
}