tableview with automatic row size based on content [closed]

Usually this is done by having a class method on your cell class that will figure out the necessary height for a given piece of content. You then call this class method in your heightForRowAtIndexPath tableview delegate method, passing in the content to the class method that will be used for that index path. Like so:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

Event* event = self.events[indexPath.row];

return [EventCell cellHeightForEvent:event];
}

In your cell height class method, you can figure out the size of your content by using methods like sizeWithFont on an NSString that you wish to display.

+ (CGFloat)cellHeightForEvent:(Event *)event {

    CGSize textSize = [event.title sizeWithFont:[UIFont fontWithNameB:@"Helvetica" size:12] constrainedToSize:CGSizeMake(67, MAXFLOAT)];

    CGFloat paddedHeight = textSize.height + 22;

    CGFloat min = 46;

    return MAX(min, paddedHeight);
}

This will cause your row height to be dynamic based on content. Note that you will have to resize your cell’s views appropriately in layoutSubviews to be correct for the size of the content for each new row.

NOTE: The answers above that suggest hardcoding specific sizes to particular index paths are a very bad solution. You may not know the number of or ordering of your data elements, which renders this solution impossible. Also, if the data set changes (in number or ordering), you then have to go back and re-code your index paths to be correct again. The solution I have given will not need to be refactored for different or dynamic data sets.

Leave a Comment