【问题标题】:AutoLayout + UITableViewCell + Height (not worked)自动布局 + UITableViewCell + 高度(不工作)
【发布时间】:2013-10-21 15:27:37
【问题描述】:

我正在尝试使用自动布局自动调整表格单元格的大小。 但似乎 TableView 忽略了高度限制。

我知道“tableView: heightForRowAtIndexPath:”可以做到这一点。

但是如何避免使用高度硬编码? 还有其他方法吗?

屏幕截图 1:

屏幕截图 2:

2

【问题讨论】:

    标签: objective-c uitableview storyboard autolayout


    【解决方案1】:
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static UITableViewCell *cell;
        if (cell == nil) {
            cell = [tableView dequeueReusableCellWithIdentifier: @"YourCell"];
        }
        [self configureCell:cell forIndexPath:indexPath]; // making text assignment and so on
        return [cell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height + 1.0f;
    }
    

    【讨论】:

    • 这通常是一个非常糟糕的主意。 tableView:heightForRowAtIndexPath: 为 tableView 中的每一行调用。如果 tableView 中有多个单元格,这将对性能产生巨大影响。
    • Matthias Bauch,这个解决方案只是改变了单元格的创建顺序。不是在“tableView:cellForRowAtIndexPath:”中创建单元格,而是在“tableView:heightForRowAtIndexPath:”中创建单元格并在“tableView:cellForRowAtIndexPath:”中重用。所以没什么好担心的。
    • 性能问题不是单元出列,也不是创建(仅发生一次)。性能下降是因为您触发了每一行的布局过程。如果此解决方案适用于您的情况,请随意使用它。但正如我所说,这通常是一个坏主意。如果您在具有数百行的 tableView 中使用这样的代码,您将感受到巨大的性能影响。 t:heightForRowAtIndexPath: 应该尽可能快地运行。
    • 如果您需要带有自动布局单元格的自定义行高,我想这是最好的解决方案。当然最好有一个预定义的行高,但它不是通用的
    • cellForRowAtIndexPath 外面打电话给dequeueReusableCellWithIdentifier,哇...不要那样做。它搞乱了UITableView 的设置方式。
    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2015-01-19
    相关资源
    最近更新 更多