2014-10-28 72 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