I have a UITableView which has been added inside a UIScrollView as part of a view controller which adheres to a part of the mockup shown below:-
As you can see
Try this
func expandCell(_ sender: UI.Button) {
if self.parent!.indexOfCellToExpand != self.tag {
print("EXPANDING...")
self.parent!.indexOfCellToExpand = self.tag
self.parent!.businessTable.reloadRows(at: [IndexPath(row: self.tag, section: 0)], with: .fade)
self.parent!.businessTable.scrollToRow(at: IndexPath(row: self.tag, section: 0), at: .top, animated: true)
}
else if self.parent!.indexOfCellToExpand == self.tag {
print("CONTRACTING...")
self.parent!.indexOfCellToExpand = -1
self.parent!.businessTable.reloadRows(at: [IndexPath(row: self.tag, section: 0)], with: .fade)
self.parent!.businessTable.scrollToRow(at: IndexPath(row: self.tag, section: 0), at: .top, animated: true)
}
// self.toggleBusinessesTable()
yourTableView.reloadData()
}
Instead of calculating heights and modifying the scroll view's .contentSize
, you can use auto-layout with a subclassed UITableView
that determines its own height:
final class ContentSizedTableView: UITableView {
override var contentSize:CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
When you change the table view - either adding / removing rows or sections, or changing the row heights - the table view's intrinsicContentSize
will be automatically updated, and its height will grow or shrink just like a multi-line UILabel
.
With the constraints setup properly, auto-layout will handle the scroll view's content size for you.