Katherine Jenkins Katherine Jenkins - 7 months ago 18
Swift Question

UITableView Cells - How to make one cell's height fixed, other cell's height variable relative to screen size?

I have a static UITableView with 1 section, 2 cells.

I would like the 'bottom' cell to be of fixed height 70 pixels and the 'top' cell of variable height - to fill the balance of screen. As follows:

enter image description here

I hav this code:

//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
}


... which works fine on my smallest screen size target (3.5 inch) where I have a total size allocation for both cells of 370 pixels.

But for larger screen sizes, my total size allocation increases. And with the above code, both cells will be displayed on a 300:70 relative ratio.

I want the size of the top cell to be variable to screen sizes - larger the screen, the greater the cell height. But the size of the bottom cell to remain a constant of 70 pixels.

Can someone please assist? Thanks very much in advance.

Answer

Your instinct is correct, you want to use heightForRowAtIndexPath.

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

If that doesn't work, comment with what went wrong and I'll modify my answer.