I have got a table in my Swift project like this
var tableView: UITableView!
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
ta
You need intrinsic cell size for this to work. Delete heightForRowAt
entirely. Your constraints in your cell should determine the cell size, this means your constraints should be at least pinned from top and bottom. Add the following code after setting the rowHeight
:
tableView.estimatedRowHeight = 250
You must delete the -heightForRow
method and set on the table view an estimatedRowHeight
.
The estimatedRowHeight
is used to calculate the bar size etc of the TV, so it should be a real value closest as possible to an average size of the table view cell height.
Now, if you are using auto layout and constraints are set correctly you should see a correct resize of your UITableViewCell
. To set correctly the constraints inside the TVC you should think to place them in a way that they can control the size of your cell.
For instance say that your TVC has just one label and that label has 4 constraints attached to its superview: top, bottom, trailing and leading with a fixed constant size. The UILabel
instance has also the numberOfLines set to 0 (means that it can expand to fill all your text).
When the autolayout engine starts to request the label intrinsicContentSize, the label will return a value that will fit all your text, the superview size will change the size according to that.
If you fix the TVC to a specific height as you did before, the TVC can't expand itself.
Pin the view's constraints to the superview's edges. Also call the estimatedRowHeight.. Remember to call a reload from the table to invoke height calculation for each cell to display.
I had problems with constraints so here is what i did.
First i added heightForRowAt
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
Then i created a variable
let tableViewHeight = postTexts.count*100
And put that in my height constraint
tableView.anchor(PostsDiv.bottomAnchor, left:view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 40, leftConstant: 15, bottomConstant: 0, rightConstant: 15, widthConstant: 0,heightConstant: CGFloat(tableViewHeight))
And it works pretty well for me