2017-01-02 56 views
2

我在UITableView中使用字幕單元格。我已在viewDidLoad以下,使該行高度自動擴展:Swift自動行高度爲字幕單元格

tableView.rowHeight = UITableViewAutomaticDimension 
    tableView.estimatedRowHeight = 100 

我還設置標題和細胞的副標題爲自動換行:

cell.textLabel?.numberOfLines = 0 
    cell.textLabel?.lineBreakMode = .byWordWrapping 

    cell.detailTextLabel?.numberOfLines = 0 
    cell.detailTextLabel?.lineBreakMode = .byWordWrapping 

當我在標題類型, 一切都很好。但小標題不會擴大該行。我還需要做些什麼才能讓字幕增加行高?

image

+0

如果您使用表格視圖單元格的標準「字幕」風格,您將有這個問題:http://stackoverflow.com/questions/36587126/autolayout-ignores-multi-line-detailtextlabel-when-calculating- uitableviewcell -h你可以覆蓋'systemLayoutSizeFittingSize:withHorizo​​ntalFittingPriority:verticalFittingPriority:'函數或者設置一個帶有約束的自定義樣式單元格(和連接的標籤而不是textLabel和detailTextLabel) – bubuxu

回答

1

通過使用此代碼https://stackoverflow.com/a/40168001/4045472和定義單元格爲:

class MyTableViewCell: UITableViewCell { 

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { 

     self.layoutIfNeeded() 
     var size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) 

     if let textLabel = self.textLabel, let detailTextLabel = self.detailTextLabel { 
      let detailHeight = detailTextLabel.frame.size.height 
      if detailTextLabel.frame.origin.x > textLabel.frame.origin.x { // style = Value1 or Value2 
       let textHeight = textLabel.frame.size.height 
       if (detailHeight > textHeight) { 
        size.height += detailHeight - textHeight 
       } 
      } else { // style = Subtitle, so always add subtitle height 
       size.height += detailHeight 
      } 
     } 

     return size 

    } 

} 

,並更改單元格的自定義類的故事板MyTableViewCell將自動設置正確的尺寸。

在表視圖數據源的tableView:cellForRow:函數中,設置標籤的文本後,調用cell.setNeedsLayout()強制其調整佈局。

+0

另一個答案只處理正在工作的主標題更改,但是這個確實在字幕改變時增加了行高。謝謝! – KJ3

4

你應該採取一個拉布勒並給予約束這樣的, enter image description here

之後,寫的tableview這個問題的兩個委託方法。

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 

因此,tableview高度按照標籤文本大小遞增。

+0

這是最好的答案 – niroshan

相關問題