Riccardo
Riccardo

Reputation: 1520

Cell content not showing up if heightForRowAtIndexPath is implemented

I'm using iOS 9.2 and XCode 7.2.

I have a basic UITableView object in which i add different kind of UITableViewCell subclasses.

With one of them, when i set manually the height overriding the method heightForRowAtIndexPath, i don't get any content on the cell.

If i return -1 as height(the default value for the UITable row height), i get my cell showing up correctly. The thing is that i do need a different height for this row because the content is quite big.

here is the code for heightForRowAtIndexPath:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MenuItem *menuItem = [menuManager menuItemAtIndex:indexPath.row];
    if ([menuItem type] == MenuItemTypeEditorHeader) {
        return 100;
    } else {
        return [super tableView:tableView heightForRowAtIndexPath:indexPath];
    }
}

MenuItem is a class containing the specific menu object' informations, such as the type. The result is that the cell is showed up at the correct height, but it's empty.

Upvotes: 0

Views: 130

Answers (3)

Luke Smith
Luke Smith

Reputation: 1320

Its not advisable to use heightForRowAtIndexPath anymore - thats old-school. Instead, do this :

  1. Set up autolayout constraints in your cell (if you dont know how to - you need to, its not something you can avoid anymore!)
  2. Create an estimatedRowHeight for autolayout to use, on the tableView. You can set it in the nib/storyboard or programmatically, in viewDidLoad for eg, like this :

self.tableview.estimatedRowHeight = 68.0;

  1. Set your tableview to use 'automatic dimension', like this :

    self.tableview.rowHeight = UITableViewAutomaticDimension;

And thats it. If you do these things, then your cells will vary in height according to their constraints. So if one of your subclasses has a height of 150px due to its constraints, that will work perfectly next to another subclass that has a height of 50px. You can also vary the height of a cell dynamically depending on the contents of the cell, for eg when you have labels that expand using 'greater than or equal to' constraints. Also - simply omit the 'heightForRowAtIndexPath' method, you dont need to implement it at all.

Upvotes: 2

phani
phani

Reputation: 130

HeightForRowAtIndexPath just returns height of a row. So may be problem in cellForRowAtIndexPath.

Upvotes: 0

TechBee
TechBee

Reputation: 1941

Are you calling tableView.reloadData() ?

print the length of menu objects before you call tableView.reloadData().

Upvotes: 0

Related Questions