扩展@Vig 的评论:
您没有指定如何确定单元格高度,所以我假设它们没有在 0 和 1 之间进行归一化。
因此,在您的UITableViewController 中,您需要以下变量:
在我的示例中,我使用 absoluteCellHeights 作为数据来确定单元格高度,这需要根据您的目的进行更改。
var absoluteCellHeights: [CGFloat] = [50, 40, 20, 10] {
didSet {
tableView.reloadData()
}
}
normalisedCellHeights 采用 absoluteCellHeights 并将它们缩放到 0 到 1 的区间内。但是,如果 absoluteCellHeights 只是充满零,则将返回 nil。
var normalisedCellHeights: [CGFloat]? {
let totalHeight = absoluteCellHeights.reduce(0, combine: +)
let normalisedHeights: [CGFloat]? = totalHeight <= 0 ? nil : absoluteCellHeights.map { $0 / totalHeight }
return normalisedHeights
}
现在在heightForRowAtIndexPath 你可以这样做:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Swift 1.2, which is why I'm using 'let' here.
let height: CGFloat
// It is assumed there is only one section.
if let normalisedHeight = self.normalisedCellHeights?[indexPath.row] {
height = normalisedHeight * tableView.frame.height
} else {
height = 50.0 // Just a random value.
}
return height
}
最后,因为您不希望表格滚动,您需要在配置表格视图时添加tableView.scrollEnabled = false。如果您使用 Storyboard,可能是 IB?
最终结果: