I am trying to make a UITableview with a footer view that fills the remaining empty space of the UITableview. However, the catch is that the cells have varying heights.
I am aware that, if the cells were all a static height, I could simply count how many cells there are and multiply that by the static height. Unfortunately, that won't work in this case.
Current solution:
Works for static height cells.
Does not work for dynamic height cells.
private func adjustFooterHeight() {
if data.count == 0 {
footerView.frame.size.height = tableView.bounds.height
}
else {
//I use data.count instead of (data.count - 1) as I have the extra hidden cell, as pictured in image 2.
let bottomFrame = tableView.rectForRow(at: IndexPath(row: data.count, section: 0))
let height = tableView.bounds.height - (bottomFrame.origin.y + bottomFrame.height - rowHeight)
footerView.frame.size.height = height < 0 ? 0 : height
tableView.reloadData()
}
}
Diagram of Intentions:

So I figured it out...
Here is the solution.
private func adjustFooterHeight() {
//Get content height & calculate new footer height.
let cells = self.tableView.visibleCells
var height: CGFloat = 0
for i in 0..<cells.count {
height += cells[i].frame.height
}
height = self.tableView.bounds.height - ceil(height)
//If the footer's new height is negative, we make it 0, since we don't need footer anymore.
height = height > 0 ? height : 0
//Create the footer
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: height))
self.tableView.tableFooterView = footerView
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With