Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing cell height in table view Objective C

Tags:

ios

iphone

I wnat my cell's height to change depending on the text being displayed in it. The text will vary and I'm basically wanting the cells to change size. Here is what I have so far:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DefaultCell1"];
    CGRect cellRectangle;
    if (cell == nil) {

    cellRectangle = CGRectMake(0.0, 0.0, 300, 110);
    cell = [[[UITableViewCell alloc] initWithFrame:cellRectangle reuseIdentifier:@"DefaultCell1"] autorelease];
    }

    UILabel *label;
    cellRectangle = CGRectMake(10, (40 - 20) / 2.0, 280, 110);

    //Initialize the label with the rectangle.
    label = [[UILabel alloc] initWithFrame:cellRectangle];
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.numberOfLines = 20;

    label.font = [UIFont fontWithName:@"Helvetica" size:11.0];
    label.text = [[self.person.statusMessages objectAtIndex:indexPath.row]   valueForKey:@"text"];
    CGFloat height = [label.text sizeWithFont:label.font].height;

    //So right here is where I think I need to do something with height and 
    //see it to something tied to he cell

    [cell.contentView addSubview:label];

    [label release];

    return cell;
}
like image 351
TheGambler Avatar asked Dec 23 '22 11:12

TheGambler


1 Answers

You shouldn't set the height in the cellForRowAtIndexPath method. there's another UITableViewDatasource method called tableView:heightForRowAtIndexPath: which you should implement to return the cell's height. Be careful using this though; you mustn't obtain the cell at that index path within this method; if you do you will construct an infinite recursive loop.

Edit: to be clear; you need to compute the cell's height based solely on it's content and not on the cell itself.

Also, in your code where you create the cell, you can just pass in CGRectZero to the frame argument; the table view will calculate the cell's frame itself if you do (and also explicitly passing in the frame is deprecated in OS 3.0 if I recall correctly).

like image 120
Kevlar Avatar answered Jan 05 '23 14:01

Kevlar