Automatic Height for UITableView into UIScrollView Swift
Insert an UITableView that takes all the height of it’s content and will be scrollable through UIScrollView
Let’s see how to insert an UITableView into a UIScrollView and make the scrollView content height based on all of the UITableView items.
First we need to create our UITableView class that we will use into our storyboards or classes. It will be very simple:
import UIKitclass TableViewAdjustedHeight: UITableView {
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return self.contentSize
}override var contentSize: CGSize {
didSet {
self.invalidateIntrinsicContentSize()
}
}override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
}
The trick here is the didSet of the contentSize that calls the invalidateIntrinsicContentSize which should be the same as the contentSize.
We also override the reloadData function because we need to call again the invalidateIntrinsicContentSize function when we refresh the data for our UITableView.