iOS 8自动调整大小的单元格与附加视图

7

使用iOS 8.3模拟器和Xcode 6.3.2。

在iOS 8中,我正在使用自动大小单元格技术,当单元格没有附件视图时,它的工作非常出色,但当单元格具有附件视图时,它会出现问题。我在单元格内部设置了标签的约束:

在UITableViewCell中使用UILabel约束

然后我使用estimatedRowHeight并将rowHeight设置为UITableViewAutomaticDimension(这里省略了tableView:numberOfRowsInSection:,但这个例子中返回3):

@implementation MyTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];

    cell.titleLabel.text = @"Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment ";

    return cell;
}

@end

然后,一切看起来都很好:

UITableView looks fine

但是当我在Storyboard中添加一个附件视图时,没有更改任何代码:

With accessory view

第一个单元格就会出现问题。 Xcode的视图调试器告诉我标签高度为1785个点,并且我必须使用gif将其显示在这里:

Huge cell

我确实注意到其他两个单元格大小正常。我还注意到,当我旋转模拟器时,第一个单元格会被正确调整大小,包括在旋转回纵向后。

有人知道为什么附件视图会导致这种严重的问题,以及我该如何解决它吗?示例项目可在http://github.com/UberJason/SelfSizingNightmare找到。

2个回答

2

这确实是一个bug。我已经将你的项目发送给了苹果公司。他们已经回复了。

enter image description here


很酷,我会在iOS 9 beta 3中检查它!我确实在beta 1或2中看过它,似乎已经修复了,尽管自适应大小的单元格在处理更复杂的布局和更多视图时仍可能有些问题。希望beta 3能使事情变得非常稳定。 - UberJason

0

这似乎是由于单元格内的标签具有 numberOfLines = 0 导致的。

虽然我不确定原因,但看起来添加附件到单元格会使自动布局无法在表格首次加载时计算标签的高度。

我通过为标签添加首选最大宽度来修复了您的示例 - 这似乎足以让布局系统及时计算出高度:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];

    // Give the layout system something to help it estimate the label height    
    cell.titleLabel.preferredMaxLayoutWidth = self.titleLabel.bounds.size.width;
    cell.titleLabel.text = @"Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment Test comment ";

    return cell;
}

或者,在viewDidAppear中调用[tableView reloadData]似乎也可以解决这个问题。


我同意附属视图是引起问题的原因。在这种情况下,设置preferredMaxLayoutWidth可能有所帮助,但我有其他稍微复杂一些的自动调整大小的单元格,并带有附属视图,其中这并没有帮助。另外,在viewDidAppear中调用[tableView reloadData]确实有效,但它会导致用户体验不佳,因为单元格会“弹”到位...总之,这个问题在iOS 9 beta中似乎得到了更好的解决,所以我只是决定不要过于担心它。 - UberJason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接