Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableview with dynamic height cells & filling footer view

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:

enter image description here

like image 297
Connor Avatar asked Jan 19 '26 13:01

Connor


1 Answers

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
    }
like image 60
Connor Avatar answered Jan 21 '26 07:01

Connor