-1

How can I make the tableview cell height dynamic, I have 1 label and 1 image in the cell, My image height is constant of 70, label height depends on the api text, if my label text I large then the image view height so table view cell should adapt label height else image View.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
}

below image just picking height of image

  • 1
    Welcome to Stack Overflow. Please take the [tour] and review [ask]. Your first step should be searching... Head over to Google (or your favorite search engine) and search for `swift uitableviewcell dynamic height`. You'll find many, many, many links to answers / articles / docs / blogs / tutorials / etc. – DonMag Oct 26 '21 at 21:00
  • Does this answer your question? [Using Auto Layout in UITableView for dynamic cell layouts & variable row heights](https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights) – jnpdx Oct 30 '21 at 01:15

1 Answers1

0

Making a UITableViewCells height dynamic based on its content is obtained by doing the following:

  1. Make sure the content of your UITableViewCell is constrained such the dynamic content is pinned to both the top and bottom of the cell.

A contrived example cell:

class Cell: UITableViewCell {
    let label = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // Allows your text to expand multiple lines
        label.numberOfLines = 0

        label.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(label)

        // Constrains a UILabel to the edges of the UITableViewCells content view
        label.topAnchor.constraint(equalTo: commentBox.topAnchor).isActive = true
        label.bottomAnchor.constraint(equalTo: commentBox.bottomAnchor).isActive = true
        label.leadingAnchor.constraint(equalTo: commentBox.leadingAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: commentBox.trailingAnchor).isActive = true
    }
}
  1. As you have above, return UITableViewAutomaticDimension from func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

  2. To help your UITableView compute the dynamic height, its recommended to return an estimated size you think your cell is going to be. func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat