一、发送通知
1 NSNotification *note = [NSNotification notificationWithName:@"通知的名称,随便写,例如:你妈叫你回家吃饭" object:self userInfo:@{ @"time":@"11:30",2 @"desc":@"回家吃饭"3 }];4 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];5 [center postNotification:note];
二、接收通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
三、键盘处理小练习
注意事项:tableView的高度约束取消,如果约束在的话,tableView无法实现上移,只能实现往上压缩
正确做法:设置tableView的高度约束等于父类约束的高度减去最下面工具栏的高度,如图:
<1>将键盘的显示和隐藏分开处理的情况
接收通知的代码:
1 - (void)viewDidLoad {2 [super viewDidLoad];3 // addObserver-谁来接收 @Selector-接收完成需要执行的方法,带一个参数,接收通知中心发来的NSNotofication对象4 // object-发送消息的对象,nil-不管谁发送的,只要是name中的消息都接收,这里监听的是键盘的即将弹出的消息,系统发出的消息是字符串常亮5 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];6 // 接收键盘隐藏的通知7 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];8 }
接收到通知后的处理代码:
1 - (void)keyboardWillShow:(NSNotification *)note 2 { 3 // 取出时间 4 CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 5 // 取出键盘显示出来后的最终frame 6 CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 7 // 改变约束 8 self.bottomSpacing.constant = rect.size.height; 9 // 动画效果10 [UIView animateWithDuration:duration animations:^{11 [self.view layoutIfNeeded];12 }];13 }14 15 - (void)keyboardWillHide:(NSNotification *)note16 {17 // 取出时间18 CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];19 // 约束改为020 self.bottomSpacing.constant = 0;21 [UIView animateWithDuration:duration animations:^{22 [self.view layoutIfNeeded];23 }];24 }
<2>将键盘显示和隐藏一起处理的情况
- (void)viewDidLoad { [super viewDidLoad]; // 接收通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];}
1 - (void)keyboardChange:(NSNotification *)note 2 { 3 // 取出时间 4 CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 5 // 取出键盘最终的frame 6 CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 7 self.bottomSpacing.constant = [UIScreen mainScreen].bounds.size.height - rect.origin.y; 8 [UIView animateWithDuration:duration animations:^{ 9 [self.view layoutIfNeeded];10 }];11 }
1 - (void)keyboardChange:(NSNotification *)note 2 { 3 // 取出时间 4 CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 5 // 取出键盘最终的frame 6 CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 7 self.bottomSpacing.constant = [UIScreen mainScreen].bounds.size.height - rect.origin.y; 8 [UIView animateWithDuration:duration animations:^{ 9 [self.view layoutIfNeeded];10 }];11 }
四、最后一步,也是最重要的一步,记得取消注册的通知监听器
- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self];}