键盘通知

** 即将出现 发送通知**

-(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];
}```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容