Friday, June 7, 2013

UITableView rowHeight example in Objective C (iOS).


UITableView rowHeight

The height of each row (table cell) in the receiver.

@property(nonatomic) CGFloat rowHeight

Discussion of [UITableView rowHeight]
The row height is in points. You may set the row height for cells if the delegate doesn't implement the tableView:heightForRowAtIndexPath: method. If you do not explicitly set the row height, UITableView sets it to a standard value.

There are performance implications to using tableView:heightForRowAtIndexPath: instead of rowHeight. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).

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

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    int cellHeight = 0;

    if ([indexPath section] == 0)
    {
        cellHeight = 16;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 20;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
else
{
    int cellHeight = 0;

    if ([indexPath section] == 0)
    {
        cellHeight = 24;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 40;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
return 0;

Example of [UITableView rowHeight].
You should avoid the heightForRowAtIndexPath if all your rows are of similar height and use the rowHeight property. According to the documentation:

There are performance implications to using tableView:heightForRowAtIndexPath: instead of rowHeight. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).

In the UITableViewController subclass it could be done, for instance, in the viewDidAppear method (the UITableViewController has a reference to the tableView):

self.tableView.rowHeight = 79.f;

UITableView rowHeight example.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [tableObj setRowHeight:100.0f];
}
Or handle it in numberOfRowsInSection: like:

- (NSInteger)tableView:(UITableView *)tblView numberOfRowsInSection:(NSInteger)section {
    [tableObj setRowHeight:100.0f];
    return [soandso count]; // soandso is my object
}

End of UITableView rowHeight example article.