A simple solution for Self Sizing TableView With Auto Resizing Cell
A couple of days ago I read a simple but brilliant article named Swift 4 recipe: Self-sizing table view by Dushyant Bansal (Link at the Bottom). What he did there was very simple and easy to understand. He overrode the reloadData()
function and the intrinsicContentSize
variable of a UITableView. The solution came handy for many applications and I used it in one of my projects. I am using some of his resources here to demonstrate what he did.
This is the Custom class he used.
The problem is, it only works for same sized cells. If we want to apply this SelfSizedTableView
class for Auto Resizing Table view cells, we need to twist the intrinsicContentSize
variable. The modified code will be like this:
override var intrinsicContentSize: CGSize {
setNeedsLayout()
layoutIfNeeded()
let height = min(contentSize.height, maxHeight)
return CGSize(width: contentSize.width, height: height)
}
Just add setNeedsLayout()
and layoutIfNeeded()
before calculating the height. And you are all set. 😆
I want to mention
If you are using pre-set data(not from API) for tableView, use tableView.reloadData()
in the viewDidAppear()
method to get the effect. If you are fetching data from API, you already use tableView.reloadData()
in the block of API response, don’t you?
Link of the article: https://bit.ly/2sKmASr
Demo Project Git Repo: https://bit.ly/2JnTouM
If this article helps you, or if it didn’t bite you 😜 give some claps. Happy Coding.