views:

3237

answers:

3

Hi everyone,

I want to create a UITableView with varying row heights, and I'm trying to accomplish this by creating UILabels inside the UITableViewCells.

Here's my code so far:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 static NSString *MyIdentifier = @"EntryCell";
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
 if (cell == nil) {
  cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
 }

    UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
 textView.numberOfLines = 0;
 textView.text = [entries objectAtIndex:[indexPath row]];
 [cell.contentView addSubview:textView];
 [textView release];

 return cell;
}

This gives me 2 lines of text per cell. However, each "entry" has a different number of lines, and I want the UITableViewCells to resize automatically, wrapping text as necessary, without changing the font size.

[textView sizeToFit] and/or [cell sizeToFit] don't seem to work.

Here's how I want the UITableView to look:

----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------

Does anyone know how to do this properly?

Thanks.

+9  A: 

The UITableViewDelegate defines an optional method heightForRowAtIndexPath, which will get you started. You then need to use sizeWithFont.

There is some discussion of your precise problem here:

http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/

Text sizing was also discussed in this thread

Airsource Ltd
that worked great, thanks. though I used sizeToFit instead of sizeWithFont.
Can Berk Güder
A: 

textView.numberOfLines = 2? numberOflines sets maximum nuber of lines so maybe 2 will owrk for u?

A: 

This code works for me. Don't know if it's perfect, but works.

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

    if(indexPath.row<[notesModel numberOfNotes]){
        NSString *cellText = [@"Your text..."];
        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:12.0];
        CGSize constraintSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 100, MAXFLOAT);
        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

        return labelSize.height + 20;
    }
    else {
        return 20;
    }
}
Olof