Reputation: 312
I've looked at a lot of examples, but somehow they don't work. My Code Below. Objects constraints in a custom cell:
Below is the code in the class:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.separatorStyle = .none
tableView.estimatedRowHeight = 200
}
//tableview ->
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 340
}
Upvotes: 0
Views: 870
Reputation: 4239
There a couple of things worth addressing:
layoutSubviews()
This method will get triggered multiple times everytime there has been a change to the layout made, meaning all of these constraints will be duplicated, and will eventually cause problems. Try to set them in init
of the cell.
heightForRowAt
When implementing this function:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 340
}
you are telling tableview to give the cell this exact size. According to documentation:
The value returned by this method takes precedence over the value in the rowHeight property.
Remove this code!
rowHeight
to automatic size valueYou have already correctly set the estimatedRowHeight
value, but we are going to also need the rowHeight
property to be set to UITableView.automaticDimension
.
tableView.rowHeight = UITableView.automaticDimension
And now you should be good to go!
Table view will benefit from any additional information on the size of the cells and you can supply that information with estimatedHeightForRowAt
if you are able to calculate a better approximate than the tableView.estimatedRowHeight
value you have set in the initial setup.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
// return more accurate value here
}
Upvotes: 1