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