Clicky

iOS Dev Nugget 313 Showing a Full Height UITableView

.

Need to run a code review on your codebase? Hire me

Sometimes it's handy to put content into UITableView and want it to stretch the full height so that all the content is displayed without scrolling. Especially if you display the UITableView in a vertical UIStackView.

class ViewController: UIViewController {
    private let tableView = UITableView(frame: .zero, style: .plain)
    private var tableViewContentSizeObserver: NSKeyValueObservation?
    lazy private var tableViewHeightConstraint = tableView.heightAnchor.constraint(equalToConstant: 0)

    func init() {
        super.init(nibName: nil, bundle: nil)
        NSLayoutConstraint.activate([
            tableViewHeightConstraint
        ])
        tableView.isScrollEnabled = false
    }

    func foo() {
        tableView.reloadData()
        tableViewContentSizeObserver = tableView.observe(\UITableView.contentSize, options: [.new]) { [weak self] (_, change) in
            guard let strongSelf = self else { return }
            guard let newSize = change.newValue else { return }
            strongSelf.tableViewHeightConstraint.constant = newSize.height
        }
    }
}

That's it. The trick is to set isScrollEnabled to false, and observe the contentSize and use the height to update the constraint.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues