iOS8中自定义UITableViewCell动态高度的内容具有不同的宽度

时间:2015-04-12 07:54:13

标签: ios objective-c xcode uitableview

我将xcode升级到6.3后遇到了这个问题。使用xcode 6.2编译的前一个版本没有这个问题,效果很好。

问题是:切换到其他标签后,或从推动segue返回后,大多数单元格的宽度会缩小一点。但有些人没有。它看起来像enter image description here

第2行单元格中的标签内容具有正确的宽度。并且所有单元格在首次启动后显示具有正确宽度的内容。 在上图中,有两个uitableviewcells。 内容视图:蓝色; 背景图:浅绿色; 内容标签:紫色;
第一个单元格中的bg视图和contentLabel缩小了。这就是我不想要的。

我使用storyboard来设置约束。 bg视图的约束。 bg view's contraints labelview的约束 enter image description here 我还尝试按照此问题UITableView layout messing up on push segue and return. (iOS 8, Xcode beta 5, Swift)缓存单元格高度,但它不起作用。

//In viewDidLoad
self.tableView.estimatedRowHeight = 100.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.contentInset = UIEdgeInsetsZero;

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    float height = [[self.estimatedRowHeightCache objectForKey:[NSString stringWithFormat:@"%ld", indexPath.row]] floatValue];
    if (height) {
        return height;
    } else {
        return UITableViewAutomaticDimension;
    }

}
//cache row height. I observed this doesn't been called in first launching in debugging.
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.estimatedRowHeightCache setValue:[NSNumber numberWithFloat:cell.frame.size.height] forKey:[NSString stringWithFormat:@"%ld", indexPath.row]];
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

为Tableview实现DataDource方法WillDisplayCell

或者你可以在单元类中实现(如果是自定义单元格)方法 - (void)awakeFromNib并设置单元格框架。

答案 1 :(得分:0)

您没有为contentView顶部的视图设置水平空间约束。您只为标签及其超级视图设置水平空间约束。

这样做

  1. 选择包含标签的视图
  2. 编辑器> Pin> SuperView的领先空间