详细实现微信输入框效果(textView 自适应文字高度)

4,571 阅读1分钟
原文链接: www.jianshu.com

前言

最近会不断推出一些轮子,这次写了一个控件,类似微信输入框,评论View,随着文字增加,textView自增长高度
如果喜欢我的文章,可以关注我微博:吖了个峥,也可以来小码哥,了解下我们的iOS培训课程。后续还会更新更多内容,有任何问题,欢迎简书留言峥吖。。。

Demo效果:


效果图.gif

Demo演示:

1.添加底部View,到最底部

  • 1.1 底部View都是显示到最下面,并且都是固定死的,采用Xib或者storyboard搭建

1.png

2.搭建底部View


2.png


3.png

3.拖线

  • 3.1 获取底部View距离底部的约束,做键盘弹出效果,底部View随着键盘弹出,而往上移动效果

4.png

    // 监听键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

    // 键盘弹出会调用
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 获取键盘frame
    CGRect endFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    // 获取键盘弹出时长
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    // 修改底部视图距离底部的间距
    _bottomCons.constant = _bottomCons.constant == 0?endFrame.size.height:0;

    // 约束动画
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}
  • 3.2 获取底部View高度的约束,当文字修改,去修改底部View整体高度

5.png


6.png

4.监听文本输入框,文字高度改变

    // 监听文本框文字高度改变
    _inputView.yz_textHeightChangeBlock = ^(NSString *text,CGFloat textHeight){
        // 文本框文字高度改变会自动执行这个block,修改底部View的高度
        // 设置底部条的高度 = 文字高度 + textView距离上下间距高度(10 = 上(5)下(5)间距总和)
        _bottomHCons.constant = textHeight + 10;
    };

源码

点击这下载源代码