iOS实现聊天输入框功能

2020-01-21 05:05:01王旭

经常使用微信聊天,没事儿就会想输入框的实现过程,所以抽空,也实现了一个输入框的功能;

ios,聊天,输入框

ios,聊天,输入框

经过封装,使用就非常的简单了,在需要的VC中,实现方法如下:


- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.00];
  
  self.keyView = [[DKSKeyboardView alloc] initWithFrame:CGRectMake(0, K_Height - 51, K_Width, 51)];
  //设置代理方法
  self.keyView.delegate = self;
  [self.view addSubview:_keyView];
}

主要就是上面的添加,此时输入框就已经添加到当前的VC中;稍后会讲到里面的代理方法的作用;

工程结构如下图

ios,聊天,输入框 

主要是红色线标出的两个类,结构比较简单

 

类名 作用
DKSKeyboardView 布局表情按钮、更多按钮、输入框
DKSTextView

设置输入行数,输入框内容变化时改变输入款高度

 

DKSKeyboardView.h中的代码如下:


#import @protocol DKSKeyboardDelegate @optional //非必实现的方法
/**
 点击发送时输入框内的文案
 @param textStr 文案
 */
- (void)textViewContentText:(NSString *)textStr;
/**
 键盘的frame改变
 */
- (void)keyboardChangeFrameWithMinY:(CGFloat)minY;
@end
@interface DKSKeyboardView : UIView @property (nonatomic, weak) id delegate;
@end

关于上面的两个代理方法,由于文章篇幅问题,实现的过程可参考demo,里面有详细的注释;

在DKSKeyboardView.m中,以下列出少量重要代码,主要是改变frame

1、点击输入框,键盘出现


//键盘将要出现
- (void)keyboardWillShow:(NSNotification *)notification {
  [self removeBottomViewFromSupview];
  NSDictionary *userInfo = notification.userInfo;
  CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
  //获取键盘的高度
  self.keyboardHeight = endFrame.size.height;
  
  //键盘的动画时长
  CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  [UIView animateWithDuration:duration delay:0 options:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] animations:^{
    self.frame = CGRectMake(0, endFrame.origin.y - self.backView.height - StatusNav_Height, K_Width, self.height);
    [self changeTableViewFrame];
  } completion:nil];
}