2014-09-26 34 views
15

所以,當我只有一個標籤根據長度改變高度時,我可以使用自動佈局設置動態高度尺寸字符串。 我的問題是,如果我添加另一個應該做同樣的UILabel,事情不會奏效。iOS 7/8 UITableView Cell:兩個具有動態高度和自動佈局以便變化行高度的UILabels

我同時設置內容抱死優先級和抗壓至1000兩個==我得到歧義

的警告,如果我設置第二個的UILabel內容抱死(垂直)爲999或250,然後它只有第二個標籤有兩行或更多行時纔有效。如果第二個標籤爲空白或只有一行,則heightForRowAtIndexPath systemLayoutSizeFittingSize:UILayoutFittingCompressedSize height將返回較大的值,並且這些單元格具有較大的空白。

我也玩過內在尺寸:默認或佔位符(有幾個高度和寬度),但它也沒有幫助。

任何有什麼建議可以做什麼?

回答

18

終於搞定了。解決方案是我明確設置首選寬度爲當前幀寬度。 因此,基本上檢查大小檢查器中標籤>首選寬度中的明確複選標記。

ref:http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout 下載示例代碼並查看故事板設置。

+0

那麼你的UILabel的固定寬度? – 2015-01-06 06:07:44

+0

不,我支持各種設備尺寸,因此寬度因此而異。 – Zsolt 2015-01-07 06:48:05

+2

對於我來說,缺少的元素是爲我的單元格的標題和字幕標籤設置內容擁抱和內容壓縮阻力優先級,如Ray Wenderlich教程中所演示的。 – Daniel 2015-01-29 08:10:59

0

對我來說,將內容擁抱優先級和內容壓縮阻力優先級降低到與預期一樣工作的元素之一。

1

對我來說,它採取了幾件事情的組合。

  • 除了設置內容擁抱和阻力正確
  • 我不得不做出的UILabel的子類來處理標籤
  • 的preferredMaxLayoutWidth並在intrinsicContentSize糾正錯誤,以及

UILabel子類最終看起來像這樣:

@implementation LabelDynamicHeight 

- (void)layoutSubviews 
{ 
    [super layoutSubviews]; 

    self.preferredMaxLayoutWidth = self.frame.size.width; 

    [super layoutSubviews]; 
} 

- (void)setBounds:(CGRect)bounds 
{ 
    [super setBounds:bounds]; 

    if (self.numberOfLines == 0) 
    { 
     CGFloat boundsWidth = CGRectGetWidth(bounds); 
     if (self.preferredMaxLayoutWidth != boundsWidth) 
     { 
      self.preferredMaxLayoutWidth = boundsWidth; 
      [self setNeedsUpdateConstraints]; 
     } 
    } 
} 

- (CGSize)intrinsicContentSize 
{ 
    CGSize size = [super intrinsicContentSize]; 

    if (self.numberOfLines == 0) 
    { 
     // There's a bug where intrinsic content size may be 1 point too short 
     size.height += 1; 
    } 

    return size; 
} 

@end 

旁邊這個調用layoutIf需要在獲取tableView heightForRowAtIndexPath:中的高度之前對單元格進行約束,以便在對contentView使用systemLayoutSizeFittingSize:方法之前使約束準備就緒。這樣看:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = ...; 
    CGFloat height = cell.frame.size.height; 
    if (cell.dynamicHeight) 
    { 
     // https://stackoverflow.com/a/26351692/1840269 
     [cell layoutIfNeeded]; 
     height = cell.frame.size.height; 

     CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
     if (size.height > height) 
      height = size.height; 
    } 
    return height; 
} 

參考文獻:

+0

它不起作用! – 2016-02-22 10:32:27

相關問題