Joel Robinson-Johnson
Joel Robinson-Johnson

Reputation: 939

Best way to set height dynamically for UITableViewCell

I have a UITableView that holds cells that can show video, html, and images, and a UI of audio playback. That's effectively 3 different cells that could potentially be in the tableView in any given point in time. Cells of the same type can have different heights. That's the problem I'm trying to solve. Out of all the tutorials I've watched/read through, none taught me how to set the calculate then set the heights dynamically. I've only read stuff that show you how to tableViews with different cells that have static heights. Any suggestions on how to solve this problem?

Upvotes: 1

Views: 42

Answers (1)

Ankit Jayaswal
Ankit Jayaswal

Reputation: 5679

Apply auto-layout in table view cell for cell-items and bound it with both top and bottom and use estimatedHeightForRowAt as:

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

Or you can manually set the height for different rows as:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50 // rather than 50 return height you need to set
}

Upvotes: 1

Related Questions