【问题标题】:Static TableViewCells Adjust Height, Fill View Height静态 TableView 单元格调整高度,填充视图高度
【发布时间】:2015-04-08 19:53:42
【问题描述】:

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

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

【问题讨论】:

  • 我会使用 -tableView:heightForRowAtIndexPath: 和 view.frame.size.height 来计算每个单元格的高度。您确实可以为您的单元格设置动态高度。您总是可以使用 % 逻辑来计算高度。例如 cell1 占视图的 25% cell2 50% cell3 10% 和 cell4 占框架高度的 15%

标签: ios objective-c uitableview swift


【解决方案1】:

扩展@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?

最终结果:

【讨论】:

  • 很棒的深度解释。感谢您的帮助
  • 我刚刚更新了我的答案,以包括absoluteCellHeights 可能只包含零的事件。但是干杯!我很高兴能帮上忙。
  • 精湛的解释和答案。谢谢!
【解决方案2】:

您可以覆盖UITableViewDelegate 方法并根据indexPath 返回每​​个单元格的自定义高度

-       (CGFloat)tableView:(UITableView *)tableView 
   heightForRowAtIndexPath:(NSIndexPath *)indexPath

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

    • 但因设备而异,除非您希望 3 到 4 个单元格中的每一个都具有潜在的独特高度。
    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    相关资源
    最近更新 更多