【问题标题】:When Exactly Does layoutSubviews get called for custom UITableViewCell?什么时候为自定义 UITableViewCell 调用 layoutSubviews?
【发布时间】:2013-02-01 06:02:48
【问题描述】:

layoutSubviews 何时在 UITableViewCells cellForRowAtIndexPath 方法中调用自定义 UITableViewCell?下面,我需要在设置FiltersTableViewCellItem 属性后调用layoutSubviews。我是否正确设置了此设置?我希望能够使用layoutSubviews,因为我听说它对性能更好。

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"FiltersTableViewCell";
    FiltersTableViewCell *filtersTableViewCell = [[self dequeueReusableCellWithIdentifier:cellIdentifier] retain];
    FiltersTableViewCellItem *filtersTableViewCellItem = [[self.filtersTableViewCellItems objectAtIndex:[indexPath row]] retain];

    if (!filtersTableViewCell)
    {
        filtersTableViewCell = [[FiltersTableViewCell alloc] initWithFiltersTableViewCellItem:filtersTableViewCellItem];
        filtersTableViewCell.delegate = self;
    }
    else
    {
        filtersTableViewCell.filtersTableViewCellItem = filtersTableViewCellItem;
    }
    return [filtersTableViewCell autorelease];
}

【问题讨论】:

  • @Danny Lin ARC 与性能改进无关。事实上,它和自动释放的效果差不多。

标签: iphone ios cocoa-touch uitableview


【解决方案1】:

layoutSubviews 在tableView:willDisplayCell: 之后的某个时间点被调用,它在tableView:cellForRowAtIndexPath: 之后被调用。您可以通过在相关方法中设置断点并查看它们被命中的顺序来验证这一点。例如,在tableView:cellForRowAtIndexPath: 的末尾设置断点。然后在FiltersTableViewCell中添加如下方法

- (void)layoutSubviews
{
    [super layoutSubviews];
}

并在那里设置断点。然后运行应用程序,看看会发生什么。

【讨论】:

  • 但是请注意,即使在willDisplayCell 之后调用layoutSubviews,这并不意味着为了调整大小而完成布局传递。我发现直到willDisplayCell 才填充的自调整单元格没有得到正确的高度,即使它还通过调用layoutIfNeeded 强制布局通过。我不得不更改我的代码以填充cellForRowAtIndexPath,而不是自动调整大小。
  • @PierreHouston 你能告诉我如何在单元格加载时在 UITableViewCell 中获取 UIButton 的大小,因为我想根据内容减小 UIButton 高度的大小。我在 iPhone 8 中制作了自定义单元。在 iPhone 5 中,我得到 UIButton 的大小与 iPhone 8 相同。请帮助我
【解决方案2】:

设置项目后尝试调用 setNeedsLayout。

filtersTableViewCell.filtersTableViewCellItem = filtersTableViewCellItem;
[filtersTableViewCell setNeedsLayout];

【讨论】:

    【解决方案3】:

    正如answer 中提到的, 有很多情况下会调用它。我还要说,当可重用项目从可重用单元队列中出列时,它可能会被调用。在寻找可重复使用的项目之前尝试设置 FiltersTableViewCellItem。

    【讨论】:

      猜你喜欢
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多