What's the correct way to have a self sizing cell in a UITableView?

Asked on 06/22/2025

1 search

To create a self-sizing cell in a UITableView, you should ensure that your cell's content is set up to automatically adjust its size based on its content. Here are some steps to achieve this:

  1. Use Auto Layout: Ensure that all the subviews within your cell are properly constrained using Auto Layout. This means setting constraints that define the size and position of each subview relative to each other and the cell's content view.

  2. Dynamic Type: If your app supports Dynamic Type, make sure to set the adjustsFontForContentSizeCategory property to true for any UILabel or text-based component. This allows the text to resize according to the user's preferred text size settings. You can learn more about this in the Get started with Dynamic Type session.

  3. Set Estimated Row Height: Set an estimated row height for your table view. This helps the table view to calculate the content size more efficiently. You can do this by setting the estimatedRowHeight property of the UITableView.

  4. Automatic Dimension: Set the rowHeight property of the UITableView to UITableView.automaticDimension. This tells the table view to use the auto layout constraints to determine the actual height of each cell.

  5. Content Compression Resistance and Hugging: Adjust the content compression resistance and content hugging priorities of your views to ensure they expand and contract as needed.

By following these steps, your UITableView cells should automatically adjust their size based on their content, providing a flexible and dynamic layout.