2014-04-22 53 views
0

我正在嘗試計算uitableviewcell的高度,而不是用boundingRectWithSize做整個舞蹈。獲取UITableViewCell類的高度而不需要子類化

這裏是我的方法:

+ (CGFloat)heightForItem:(id<DDInfoItem>)item 
{ 
    if (!PrototypeCell) 
     PrototypeCell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil][0]; 

    [PrototypeCell configureForItem:item]; 
    [PrototypeCell layoutIfNeeded]; 

    CGSize size = [PrototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
    return size.height+1; 
} 

不幸的是,這條線

CGSize size = [PrototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 

將返回零...我懷疑,因爲我還沒有建立自己的約束,因爲這不是一個子類的UITableViewCell。有人可以確認嗎?在這種情況下,有沒有一種簡單的方法讓細胞調整自己?

謝謝!

UPDATE

我還在一個高度背得0甚至以爲我已經子類和IB增加了約束。

下面是我對內容查看的限制看起來像在調試器:

<NSLayoutConstraint:0x170091030 H:|-(NSSpace(20))-[UILabel:0x12766b610] (Names: '|':UITableViewCellContentView:0x178361380)>, 
<NSLayoutConstraint:0x170094370 V:|-(NSSpace(20))-[UILabel:0x12766b610] (Names: '|':UITableViewCellContentView:0x178361380)>, 
<NSLayoutConstraint:0x1700992d0 H:[UILabel:0x12766b610]-(NSSpace(20))-| (Names: '|':UITableViewCellContentView:0x178361380)>, 
<NSLayoutConstraint:0x170099500 V:[UILabel:0x12766b610]-(NSSpace(8))-[UILabel:0x127559c20]>, 
<NSLayoutConstraint:0x170099000 H:[UILabel:0x127559c20]-(NSSpace(20))-| (Names: '|':UITableViewCellContentView:0x178361380)>, 
<NSLayoutConstraint:0x17009c430 H:|-(NSSpace(20))-[UILabel:0x127559c20] (Names: '|':UITableViewCellContentView:0x178361380)> 

請注意,我已經取代了原型細胞的initWithStyle:標識符:用筆尖加載方法。

此外,當我記錄標籤的大小,他們確實似乎正確調整大小。調用systemLayoutSizeFittingSize的結果仍然給我一個0的高度,但是:/

+0

你的代碼看起來與約束的細胞正確。但是,'UITableViewCell'沒有任何限制。 – CrimsonChris

+0

不要忘記將原型單元格的寬度設置爲表格視圖的寬度。 – CrimsonChris

+0

啊好的。多數民衆贊成在我正在尋找。感謝 –

回答

0

您可能在過程中要求高度過早。高度爲0,因爲那時高度尚未確定。

0

對於它的價值,我結束了什麼只是這樣做:

if (!PrototypeCell) 
    PrototypeCell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil][0]; 

[PrototypeCell configureForItem:item]; 
[PrototypeCell setNeedsLayout]; 
[PrototypeCell layoutIfNeeded]; 

return CGRectGetMaxY(PrototypeCell.subLabel.frame) + bottomBufferSpacing; 
+0

那有用嗎?對於每個細胞?似乎是 – matt

+0

。這些標籤似乎正確地放置了自己,但無論出於何種原因,單元格的contentView似乎都不知道我希望它調整大小以適應子視圖。我可能會在某個地方錯過/誤解某個約束 –

相關問題