Rohit Chouhan
Rohit Chouhan

Reputation: 67

Self-sizing table view cell with title and detail fields

I am trying to make a UITableView where the cells automatically resize to the size of the content in each cell. I have seen a bunch of other questions about this but they mainly deal with cells that have just a title label. When I only have one label, the resizing works, but when I use a cell with the "right detail" style, I have issues again.

This is what my view looks like.

I have tried to set both the title and detail labels to have 0 number of lines so they both resize themselves, but for some reason this is not resizing the actual tableView cell.

Upvotes: 0

Views: 86

Answers (1)

Cedan Misquith
Cedan Misquith

Reputation: 1154

You need to set your constraints right for both labels in the cell. Make sure your title label has a left and top constraint to the content view, and a right constraint to details label. Make sure details label has top, right and bottom constraint to content view.

Then in your code, you need to set the height for each cell. Use this function.

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

Here the UITableViewAutomaticDimension will make the cell height resize to the content height of your label.

Note: Keep numberOfLines for details label as 0

Upvotes: 2

Related Questions