2014-10-28 33 views
3

我想要计算iOS 7中我的uitableviewcell子类的高度,我发现在第一遍时计算不正确。但是,如果我稍后重新载入表格视图,则第二遍计算确实是正确的。这里是我正在计算单元格高度:iOS 7不正确的UITableViewCell第一遍高度的计算

if (_prototypeHeader == nil) { 
      _prototypeHeader = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([DDStatusTableViewCell class]) owner:nil options:0] lastObject]; 
    } 
    [_prototypeHeader setFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 0)]; 
    [_prototypeHeader configureForMenu:self.menu atRestaurant:self.restaurant]; 
    [_prototypeHeader setNeedsLayout]; 
    [_prototypeHeader layoutIfNeeded]; 

    CGSize size = [_prototypeHeader.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
    NSLog(NSStringFromCGSize(size)); 
    return size.height + 1; 

日志语句记录本作的大小:

2014-10-28 10:15:45.492 MyApp[39252:613] {350, 77} <--- this is incorrect 
2014-10-28 10:15:46.495 MyApp[39252:613] {294, 110} <--- this is correct 

我也注销在两种情况下的实现代码如下宽度和它似乎是一致的320.这只是iOS 7中的一个问题。什么给了?

谢谢!

编辑

经过进一步检查,我已经决定了我顶标签的布局宽度不正确。在标签的layoutSubviews方法,我这样做:

- (void)layoutSubviews { 
    [super layoutSubviews]; 
    self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width; 
    self.detailLabel.preferredMaxLayoutWidth = self.detailLabel.frame.size.width; 
    [super layoutSubviews]; 
} 

在第一遍时,titleLabel的宽度为170,而在第二遍,宽度为130仍在试图找出原因。 contentView的宽度在第一遍时也是360,第二遍缩小到320。似乎调整标签宽度的布局代码发生在contentView调整其大小之前。

回答

3

要求单元格在更改preferredMaxLayoutWidth之前布局contentView似乎有诀窍。

- (void)layoutSubviews { 
    [super layoutSubviews]; 
    [self.contentView layoutIfNeeded]; 
    self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width; 
    self.detailLabel.preferredMaxLayoutWidth = self.detailLabel.frame.size.width; 
    [super layoutSubviews]; 
} 
+0

我在iOS7上有完全相同的问题;在iOS 8上,一个非常类似的问题是,尽管contentView的帧大小正确,但是在第二次或第三次传递之前,子视图(顶部/底部/顶部/尾部固定到contentView)没有正确的帧大小。 你的技巧来调用'contentView.layoutIfNeeded()'这两个技巧! – 2015-08-08 13:59:16

+0

但为什么它的行为如此呢?它必须在layoutSubviews中正确计算,不是吗? – sacred 2016-08-22 15:44:11