美文网首页
iOS开发 - tabCell中的UITextView跟随输入实

iOS开发 - tabCell中的UITextView跟随输入实

作者: 俺不是大佬儿 | 来源:发表于2021-10-15 20:34 被阅读0次
项目中有信息提交表单,表单中的详细地址信息字数长度没有明确限制,输入中有需要换行的需求如下图
表单列表
只需要两步就可以实现平滑的高度自适应

前提条件是需要将 textView默认的可滚动属性关闭

self.info_textView.scrollEnabled = NO;

第一步:

在- (void)textViewDidChange:(UITextView *)textView代理方法或通知监听方法中计算textView的动态输入高度

- (void)textViewDidChange:(UITextView *)textView {
    if(textView == self.info_textView){
        CGRect  tvBounds   = self.info_textView.bounds;
        CGFloat tvHeight   = CGFLOAT_MIN;
        CGFloat cellHeight = self.viewModel.rowHeight;
        tvHeight = tvBounds.size.height;
        
        //计算 text view 的高度
        CGSize maxSize = CGSizeMake(tvBounds.size.width, CGFLOAT_MAX);
        //获取textView的当前输入文本的 size
        CGSize newSize = [self.info_textView sizeThatFits:maxSize];
        tvBounds.size = newSize;
        //判断当前的输入高度是否有变化
        if(tvHeight != tvBounds.size.height){
            self.info_textView.bounds = tvBounds;
            tvHeight = tvBounds.size.height;
           //当前的  cell高度 = textView的适时高度 + cell中的控件固定高度间隔(cellFixedHeightSpace)
            cellHeight = tvHeight + cellFixedHeightSpace;
            cellHeight = (cellHeight > self.viewModel.rowHeight ? cellHeight : self.viewModel.rowHeight);
           //设置新的cell高度
            self.viewModel.rowHeight = cellHeight;
            //对外发送高度变化信号 通知VC更新页面
            [self.viewModel.textViewHeightDidChangeSub sendNext:RACTuplePack(self.viewModel.cellIndexPath,@(tvHeight),@(cellHeight),self.info_textView.text)];
        }
    }
}

第二步:

在vc中接收cell高度变化的信号/通知/block 进行tableView的更新

//接收cell文本输入高度变化的信号 适时更新tableView
@weakify(self);
[self.viewModel.addressCellHeightDidChangeSub subscribeNext:^(RACTuple  *_Nullable tup) {
        @strongify(self);
        [self.tableView beginUpdates];
        [self.tableView endUpdates];
   }];

以上两步就能实现tabcell的UITextView输入中高度平滑自适应,我用的是MVVW+RAC的框架模式欢迎交流沟通!

相关文章

网友评论

      本文标题:iOS开发 - tabCell中的UITextView跟随输入实

      本文链接:https://www.haomeiwen.com/subject/cogmoltx.html