** 即将出现 发送通知**
-(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];
}```
** 键盘弹起修改动画**
-(void)openKeyboard:(NSNotification *)sender{
- 弹起高度
CGFloat keyboardHeight = [sender.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue].size.height;
- 动画时长
CGFloat duration = [sender.userInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue];
- 动画种类
NSInteger option = [sender.userInfo[UIKeyboardAnimationCurveUserInfoKey]intValue];
- 修改约束
self.bottomLayoutConstraint.constant = keyboardHeight;
[UIView animateWithDuration:duration delay:0 options:option animations:^{
[self.view layoutIfNeeded];
//键盘弹起后滚动到最底部
[self scrollToTableViewLastRow];
} completion:nil];
}```
** 关闭键盘修改动画**
-
(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];
}```
** 点击右下角返回按键,发消息,收键盘**
- (IBAction)clickReturnKey:(UITextField *)sender {
NSString *newContent = self.textField.text;
if (newContent.length == 0) {
return;
}
//构建message对象
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];
}```
**控制表视图滚动到最底部**
-(void)scrollToTableViewLastRow{
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:self.allMessage.count-1 inSection:0];
[self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}```