静态TableViewCells调整高度,填充视图高度

时间:2015-04-08 19:53:43

标签: ios objective-c uitableview swift

我的应用程序需要一些UITableViews做得更简单的事情。我遇到了这个问题:我希望底部单元始终位于视图控制器的底部,我希望所有单元格动态调整它们的高度,以便每个单元格都适合视图控制器内部,不需要滚动看到更多细胞。

基本上我想要3或4个大的tableViewCell,它们都根据正在使用的设备动态改变高度。警告:所有这些细胞需要不同的高度。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

扩展@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。如果您正在使用故事板,可能是IB?

最终结果:

enter image description here

答案 1 :(得分:0)

您可以覆盖UITableViewDelegate方法,并根据indexPath

为每个单元格返回自定义高度
-       (CGFloat)tableView:(UITableView *)tableView 
   heightForRowAtIndexPath:(NSIndexPath *)indexPath

答案 2 :(得分:0)

在这个委托方法中,只需返回UITableView的高度除以UITableView中的行数。

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    return tableView.frame.size.height / tableView.numberOfRowsInSection(0)
}

(0)假设您的表视图中只有一个部分。

相关问题