【发布时间】:2023-03-29 15:05:02
【问题描述】:
我有一个静态 UITableView,有 1 个部分,2 个单元格。
我希望“底部”单元格的高度固定为 70 像素,而“顶部”单元格的高度可变 - 以填充屏幕的平衡。如下:
我有这个代码:
//Modify TableView Cell Heights For Screen Sizes:
var absoluteCellHeights: [CGFloat] = [300, 70] {
didSet {
tableView.reloadData()
}
}
var normalisedCellHeights: [CGFloat]? {
let totalHeight = absoluteCellHeights.reduce(0) { $0 + $1 }
let normalisedHeights: [CGFloat]? = totalHeight <= 0 ? nil : absoluteCellHeights.map { $0 / totalHeight }
return normalisedHeights
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let height: CGFloat
if let normalisedHeight = self.normalisedCellHeights?[indexPath.row] {
height = normalisedHeight * tableView.frame.height
} else {
height = 50.0 // Just a random value.
}
return height
}
...在我最小的屏幕尺寸目标(3.5 英寸)上工作正常,我为两个单元格分配了 370 像素的总尺寸。
但是对于更大的屏幕尺寸,我的总尺寸分配会增加。使用上面的代码,两个单元格将以 300:70 的相对比例显示。
我希望顶部单元格的大小随屏幕大小而变化 - 屏幕越大,单元格高度越高。但底部单元格的大小要保持不变,为 70 像素。
有人可以帮忙吗?提前非常感谢。
【问题讨论】:
-
为什么你使用一个表格视图而不是只有两个布局约束的视图?
-
这是一个很好的问题。本质上,我有一系列不同的 TableViewControllers - 有些有 2 个单元格,有些有更多。但底部单元格的高度始终不变。
-
^也同意。如果您的表格视图不是动态的,只需使用两个视图,一个高度约束为 70,另一个固定到其余边缘。
标签: ios swift uitableview height tableviewcell