** 即將出現(xiàn) 發(fā)送通知**
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openKeyboard:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeKeyboard:) name:UIKeyboardWillHideNotification object:nil];
}```
** 即將消失,銷毀通知**
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}```
** 鍵盤彈起修改動(dòng)畫**
-(void)openKeyboard:(NSNotification *)sender{
- 彈起高度
CGFloat keyboardHeight = [sender.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue].size.height;
- 動(dòng)畫時(shí)長(zhǎng)
CGFloat duration = [sender.userInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue];
- 動(dòng)畫種類
NSInteger option = [sender.userInfo[UIKeyboardAnimationCurveUserInfoKey]intValue];
- 修改約束
self.bottomLayoutConstraint.constant = keyboardHeight;
[UIView animateWithDuration:duration delay:0 options:option animations:^{
[self.view layoutIfNeeded];
//鍵盤彈起后滾動(dòng)到最底部
[self scrollToTableViewLastRow];
} completion:nil];
}```
** 關(guān)閉鍵盤修改動(dòng)畫**
-
(void)closeKeyboard:(NSNotification *)sender{
CGFloat duration = [sender.userInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue];
NSInteger option = [sender.userInfo[UIKeyboardAnimationCurveUserInfoKey]intValue];
self.bottomLayoutConstraint.constant = 0;[UIView animateWithDuration:duration delay:0 options:option animations:^{
[self.view layoutIfNeeded];
} completion:nil];
}```
** 點(diǎn)擊右下角返回按鍵暇榴,發(fā)消息攒盈,收鍵盤**
- (IBAction)clickReturnKey:(UITextField *)sender {
NSString *newContent = self.textField.text;
if (newContent.length == 0) {
return;
}
//構(gòu)建message對(duì)象
Message *newMessage = [[Message alloc]init];
newMessage.content = newContent;
newMessage.fromMe = YES;
//將新的message保存到模型中
[self.allMessage addObject:newMessage];
self.textField.text = @"";//清空文本框
//局部刷新界面
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.allMessage.count-1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self scrollToTableViewLastRow];
}```
**控制表視圖滾動(dòng)到最底部**
-(void)scrollToTableViewLastRow{
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:self.allMessage.count-1 inSection:0];
[self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}```