PAULMAX
PAULMAX

Reputation: 312

How to programmatically adjust the height of a cell in a TableView if everything is created programmatically, without using a storyboard?

I've looked at a lot of examples, but somehow they don't work. My Code Below. Objects constraints in a custom cell:

enter image description here

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

Answers (1)

Witek Bobrowski
Witek Bobrowski

Reputation: 4239

There a couple of things worth addressing:

1. Do not setup your layout in 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.

2. Do not implement 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!

3. Set rowHeight to automatic size value

You 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!

Bonus: Scrolling Performance improvements

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

Related Questions