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
.
.