【问题标题】:Automatically Resize Custom UITableViewCell自动调整自定义 UITableViewCell 的大小
【发布时间】:2016-06-10 14:30:23
【问题描述】:

我有一个自定义表格视图单元格,我想根据标签中的文本量自动调整其大小。

这是我的牢房。我想调整它的大小以显示评论标签中的所有文本。

在我的表格视图控制器中,我使用 UITableViewAutomaticDimension

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return 200
            } else {
                return 49
            }
        } else if indexPath.section == 1 {
            return 100
        } else if indexPath.section == 2 {
            if indexPath.row == 0 {
                return 200
            } else {
                return 400
            }
        } else {
            return UITableViewAutomaticDimension
        }
    }

    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

这就是我最终的结果。

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

在委托函数中实现高度计算:

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
   let cell = tableView.cellForRowAtIndexPath(indexPath)
   let size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
   return size.height + 1.0 // Add 1.0 for the cell separator height
}

【讨论】:

    【解决方案2】:

    你需要:

    1. 为您的标签 top, trailing, leading, bottom 设置约束到 IB 中的 superView
    2. 设置numberOfLines = 0
    3. 设置Content Compression Resistance Priority VerticalContent Hugging Priority Vertical
    4. 在代码中设置self.tableView.estimatedRowHeight = MinControlSize;self.tableView.rowHeight = UITableViewAutomaticDimension;

    设置文本后调用这个

    cell.setNeedsDisplay();
    cell.layoutIfNeeded();
    

    在委托方法中

    optional func tableView(_ tableView: UITableView,
    heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    

    希望对您有所帮助。我从 Apple 的 Self Sizing 示例中获取了这个

    【讨论】:

      【解决方案3】:

      确保您从子 UIView 或您拥有的任何子元素为 contentView 的顶部、底部、尾部和前导边距设置了约束。这可能对你有帮助

      在您的情况下,您需要定义从 ReviewLabel 到 contentView 的底部间距约束以使其工作。相应的UILabels 也需要顶部、尾部和前导边距。顶部空格可以从 DateLabel 中定义,而前导和尾随空格可以从包含星星的 UIView 中定义

      为什么?

      contentView 需要了解其子视图的框架,以便 uitableviewautomaticdimension 对其进行处理。如果它不知道它的子视图框架,那么它就不会知道自动调整大小到什么

      【讨论】:

        猜你喜欢
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-16
        相关资源
        最近更新 更多