Peter Kazazes
Peter Kazazes

Reputation: 3628

Dynamically sized UITableViewCells

I'm relatively new to iOS development and I have a question that I'm sure the answer to is quite simple.

I have an NSArray populating a UITableView. It's working perfectly, however I have to manually set the height of each cell. Having a set height makes short amounts of text looks bad and cuts off large amounts of text.

I know there is a way to dynamically resize the cell height. I see it done all the time in apps. I also know that it involves the heightForRowAtIndexPath portion of the Table View delegate.

How should I take the objectAtIndexPath and estimate the size of it in order to accurately size the cell?

Upvotes: 1

Views: 163

Answers (2)

Nielsou Hacken-Bergen
Nielsou Hacken-Bergen

Reputation: 2626

Populate your datasourceArray with dictionaries to do something like this :

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"heightForTheCell"];
}

where you specify the specific size of each row. My example work with only one section, but it gives you a good idea of the code to write.

Upvotes: 1

user23743
user23743

Reputation:

One simple - yet slow - way which I always use as a first stab is to actually configure the cell and then find out how high it is. You might find that unacceptable for your app's performance, at which point you can look at which bits of the layout logic can be separated out just to work out the height.

Upvotes: 1

Related Questions