TextView&的动态单元格大小ImageView在同一个单元格中

时间:2018-04-23 04:52:18

标签: ios swift uitableview

我有ImageViewTextView我需要动态单元格大小,这取决于textView内部是否有更多文字。

我正在使用UITableViewAutomaticDimension

enter image description here enter image description here

用户界面示例:

cell正在扩展文字金额,但未扩展UIImage。我究竟做错了什么?我应该如何添加约束以适应这种情况?如果您需要更多信息,请与我们联系。

enter image description here

图像低于storyBoard中的固定单元格大小。

如果我添加底部约束,其中红色圆圈位于第二个图像中,则textView文本仅在一行上且不再是动态的。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {


        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableViewAutomaticDimension
    }

如果我在superView textView中添加底部不再动态。 (与上图相比。)

在尝试让它们协同工作时,底层约束是我的主要问题。

enter image description here

2 个答案:

答案 0 :(得分:4)

如果您正在使用自动布局,有一种更简单的方法可以在没有任何计算的情况下执行此操作,因此您也可以忘记heightForRowAtIndexPath委托,只需让自动布局完成其工作。

诀窍,诀窍的关键只有三件事:

在单元格内容上设置所需的自动布局参数。

  1. 在tableview单元格高度上启用UITableViewAutomaticDimension。

  2. 为tableview提供一些预估编号(用于优化滚动速度)。

  3. 在单元格内容上设置所需的自动布局参数

  4. 请记住规则是表视图单元格上的所有项目都需要固定在父视图的top, bottom,leadingand trailing边缘上。例如,如果您的表格视图单元格有两个标签:brandNameLabel & brandAddressLabel,那么这些标签的布局将为:

    对于brandNameLabel:

    enter image description here

    适用于brandAddressLabel:

    enter image description here

    有关详情,请参阅此REFERENCE

    完成自动布局后,在viewdidLoad()方法中添加以下两行代码

    tableView.estimatedRowHeight = 100 //just give an estimated size based on your data tblAmount.rowHeight = UITableViewAutomaticDimension

    你完成了。现在,单元格将自动调整为单元格的内容。

答案 1 :(得分:0)

尝试像这样设置 UIImage 约束。

enter image description here

尾随,前导,顶部,底部和固定高度,宽度。

还要写 UITableViewDelegate 方法。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }