ios - UITableView Cells - 如何使一个单元格的高度固定,其他单元格的高度相对于屏幕尺寸可变?

标签 ios swift uitableview height tableviewcell

我有一个包含 1 个部分、2 个单元格的静态 UITableView。

我希望“底部”单元格的高度固定为 70 像素,而“顶部”单元格的高度可变 - 以填充屏幕的平衡。如下:

enter image description here

我有这段代码:

//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 像素。

有人可以帮忙吗?非常感谢。

最佳答案

这应该有效:

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
}

关于ios - UITableView Cells - 如何使一个单元格的高度固定,其他单元格的高度相对于屏幕尺寸可变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37035547/

相关文章:

ios - UIButton 以编程方式在 UITableView 的一部分中创建,以隐藏/显示该部分的内容

ios - Swift - tableviewcell 使用自定义单元返回空

objective-c - arrayWithObjects 和 initWithObjects 有什么区别?

swift - 获取相同路径下载的文件但无法打开该文件

xcode - UITabBarItem 在触摸时增长

swift - 使用照片框架删除相机胶卷 Assets

ios - SIRI 不会根据提供的参数回复,而是打开 "Shortcut"应用程序

iOS - 遍历单元格并检索数据

ios - 最初使用非零值调用的 numberOfRowsInSection

iphone - 我应该使用什么类型的 iPhone 应用程序文件?