【问题标题】:UITableView Cells - How to make one cell's height fixed, other cell's height variable relative to screen size?UITableView Cells - 如何使一个单元格的高度固定,另一个单元格的高度相对于屏幕尺寸可变?
【发布时间】: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


【解决方案1】:

这应该可行:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    var height: CGFloat

    if indexPath.row == 1 {
        height = 70.0
    } else {
        height = tableView.frame.height - 70.0
    }

    return height
}

【讨论】:

    【解决方案2】:

    你的直觉是正确的,你要使用heightForRowAtIndexPath

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 1 { return 70 }
        else { return tableView.frame.size.height - 70 }
    }
    

    如果这不起作用,请评论出了什么问题,我会修改我的答案。

    【讨论】:

    • 啊。这么简单;)默认情况下,这将基本上返回行的任何其他单元格!= 1 来填充屏幕的平衡?我会尝试并报告。
    • 如果您有两个以上的单元格,您可以简单地将检查更改为:if indexPath.row == self.data.count - 1 其中data 是您提供给表格视图的日期数组。
    • 绝妙的逻辑。值得拥有丝带和蝴蝶结;)非常感谢。非常适合我的需求!
    • 如果您的表格视图内容不是动态的,除非您需要表格视图附带的外观和感觉,否则我建议您使用简单视图的自动布局。
    • 你能详细说明一下吗?我将为当前包含两 (2) 个表格视图单元格的所有 TableViewControllers 采用带有几个布局约束策略的两 (2) 个 UIViews(感谢@Wain)——这对我来说更简单。但还有其他原因吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多