werbary
werbary

Reputation: 1095

Height of uitableview by number of rows in title

I have this code, but it's crashing.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.textLabel.numberOfLines == 2) {
        return 100;
    } else {
        return 80;
    }
}

Problem is here:

UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];

Upvotes: 1

Views: 332

Answers (2)

chown
chown

Reputation: 52788

Try using the table views data source method [self tableView:tableView cellForRowAtIndexPath:indexPath] instead:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    if (cell.textLabel.numberOfLines == 2) {
        return 100;
    } else {
        return 80;
    }
}

Upvotes: 2

Tom
Tom

Reputation: 1349

I guess you built some infinite recursion here. When you are asked about the height, your are requesting the cell which is requesting the height ... You should do your calculation based on your data model not on the cell itself.

Upvotes: 4

Related Questions