So what i want to do is to have a tableview that maxes out it sizes while respecting autolayout constraints. Right now i have a tableview that maxes out it is size, but its not scrollable.
public class ExpandingTableView2: UITableView {
override public func reloadData() {
super.reloadData()
self.setNeedsLayout()
self.invalidateIntrinsicContentSize()
}
override public func layoutSubviews() {
super.layoutSubviews()
if !self.bounds.size.equalTo(self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override public var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
let intrinsicContentSize = super.contentSize
return intrinsicContentSize
}
}
You can calculate the tableview height based on the content size by creating an outlet for height contraint:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableViewHeightConstraint.constant != tableView.contentSize.height && tableViewHeightConstraint.constant < view.frame.height // This will prevent to increase tableview height beyond the view and let it scroll
{
setupHeightConstraintForTableView(tableView.contentSize.height)
}
// rest of the code
}
func setupHeightConstraintForTableView(_ heightValue: CGFloat) {
tableViewHeightConstraint.constant = heightValue
self.updateConstraintsIfNeeded()
}