我有一个TableViewController,它包含三个不同的自定义单元格。对于第一个单元格,我想包含一个水平滚动的CollectionView,第二个单元格包含一个CollectionView,第三个单元格包含一个垂直的CollectionView。我写我的代码是这样的:Swift:如何在包含多个单元格的TableViewController中设置动态单元格高度
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell1") as! HomePageTableViewCell1
return cell
}
else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell2") as! HomePageTableViewCell2
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell3") as! HomePageTableViewCell3
return cell
}
}
它的工作原理就像我想的,但我不确定这是实现我想要的最好方法吗?因为我对Swift很陌生,也许有更好的方法来做到这一点?其次,对于这三个单元格,我想保留一个基于内容的动态高度。例如,第一个单元格包含一个ImageView,其高度为260,第二个单元格包含一个高度为140的ImageView。第三个单元格中包含的CollectionView将返回4行,每行中,有一个与高度96.我已经做了ImageView的是:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return 260
}
else if indexPath.section == 1 {
return 140
}
else {
return 500
}
}
但这意味着我必须硬编码这些高度在我知道内容的高度。但是如果我不知道身高,比如说第三个细胞会返回5排,这意味着500不够,那么我应该怎么做才能给细胞提供一个动态的高度。
使用heightforRowAtIndexPath设置每个单元的高度 –
如何识别各小区?使用'indexPath.section'? –
是使用indexpath.section == 0像这样,管理每个单元格的高度的最佳方法 –