0
基本上,我有一個包含10個標籤的單元格,目前我已將其高度固定爲300.但是,標籤可能有或沒有價值,如果標籤沒有特定的值,則需要隱藏它們。檢查每個標籤的零條件,然後調整高度同樣是漫長而雜亂的。有沒有其他方法可以實現我在找的東西? 如何調整自定義UITableViewCell的大小以適應內容?
基本上,我有一個包含10個標籤的單元格,目前我已將其高度固定爲300.但是,標籤可能有或沒有價值,如果標籤沒有特定的值,則需要隱藏它們。檢查每個標籤的零條件,然後調整高度同樣是漫長而雜亂的。有沒有其他方法可以實現我在找的東西? 如何調整自定義UITableViewCell的大小以適應內容?
這是一個想法的例子,我會建議。我希望這可以幫助你爲你找到一個優化的。
如果我假設,你的數據來源是這樣的:
// array of arrays of strings
var Array : [[String]] = [
["Label1", "Label2", "Label3", "Label4"],
["Label1", "Label2"],
["Label1", "Label2", "Label3", "Label4", "Label5", "Label6"],
]
這些方法可以實現:
func calculateExpectedHeight(withItemsCount: Int) -> CGFloat
{
let titleHeight = 32.0 // this is e.g. your Layer Conf. label
let itemHeight = 18.0 // this is for a label unit that is repeating
return CGFloat(titleHeight) + CGFloat((Double(withItemsCount) * itemHeight)) + 12.0 //twelve is just for tuning
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let dataForThisRow = Array[indexPath.row]
return calculateExpectedHeight(withItemsCount: dataForThisRow.count)
}
使用自動佈局到您的所有標籤的限制表視圖單元格。然後在你的表格視圖委託中,爲'heightForRowAt'和'estimatedHeightForRowAt'返回'UITableViewAutomaticDimension'。有了這些東西,桌子/單元將爲您處理尺碼。 – keithbhunter
限制所有標籤到tableviewcell?你能詳細說明一下嗎? –
通讀如何使用自動佈局。這是你需要的。 [蘋果網站上的文章](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/)和[Ray Wenderlich教程](https://www.raywenderlich.com/115440/)自動佈局教程合IOS-9-部分-1-工具入門-2)。 – keithbhunter