How to add optional elements in tableViewCell

Hi,


How can I create a tableViewCell with a lot of elements, but having the cell increase/decrease height dependent on which elements that are present?


I.e: I always have an image and a title, but I could also have subtitle, tags, an icon + +. If I only have image and title, I want the title to be aligned to the center of the image, and the cell to be e.g 80 height. But If I have subtitle and tags, I want the height to be higher and the title to align to the top line of the image with tags and subtitles below.

Accepted Reply

You should implement optional delegate func


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat


Then you have 2 options:

- use a xib and have all elements present in the xib, hidden or visible depending on cell

In heightForRowAt, evaluate what is the required height, depending on visible items.

To adjust layout, you could create IBOutlets for the constraints at stake and adapt their value in cellForRow


- build the cell completely in code

then you have also to create the constraints

and you can compute the required height


I prefer first approach.

Replies

You should implement optional delegate func


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat


Then you have 2 options:

- use a xib and have all elements present in the xib, hidden or visible depending on cell

In heightForRowAt, evaluate what is the required height, depending on visible items.

To adjust layout, you could create IBOutlets for the constraints at stake and adapt their value in cellForRow


- build the cell completely in code

then you have also to create the constraints

and you can compute the required height


I prefer first approach.

Ah, I didn't know I could create IBOutlets for constraints 🙂


Thanks!