如何讓 Static Cells 自動計算高度

使用 Static Cells 製作表格時,我們可在 storyboard 快速地設定表格內容,而不用麻煩地定義 UITableViewDataSource 的相關 function。

然而當我們希望 cell 利用 auto layout 條件自動計算高度時,卻會遇到問題,例如以下例子:

如上圖所示,我們將 cell 裡的 label 設為顯示多行文字,上下左右的間距設為 10。

我們預期最後表格顯示時,cell 的高度將為 label 顯示完整內容後,上下分別額外加 10 的高度,但 App 執行後卻如下圖所示,無法完整顯示李商隱的經典情詩。

怎麼會這樣呢 ?

這是因為當表格為 Static Cells 時,cell 預設顯示的高度將為我們在 storyboard 裡看到的 cell 高度,因此如下圖所示,剛剛的 cell 高度將為 100,絲毫不受 auto layout 的影響。

想讓 Static Cells 的 auto layout 條件發揮作用,有以下兩個方法。

方法一

  • table view 的 row height & estimate 勾選 Automatic。
  • table view cell 的 row height 勾選 Automatic。

方法二

在 viewDidLoad 將 table view 的 estimatedRowHeight 設為 UITableView.automaticDimension。

override func viewDidLoad() {
super.viewDidLoad()

tableView.estimatedRowHeight = UITableView.automaticDimension

}

另外目前測試當表格是 static cell 時,設定 tableView.rowHeight = UITableView.automaticDimension 沒有用,因此我們必須再定義 UITableViewDelegate 的 function tableView(_:heightForRowAt:)。回傳 UITableView.automaticDimension。

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}

ps:

別忘了在 controller 裡移除 function numberOfSections(in:) & tableView(_:numberOfRowsInSection:),因為我們希望 Static Cells 的 cell 數量由 storyboard 控制,而不是程式。

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com