9

I can't seem to get the text to actually span multiple lines. The heights look correct. What am I missing?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell =  [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"StatusCell"] autorelease];

    CGRect frame = cell.contentView.bounds;
    UILabel *myLabel = [[UILabel alloc] initWithFrame:frame];
    myLabel.text = [[person.updates objectAtIndex:indexPath.row] valueForKey:@"text"];
    [cell.contentView addSubview:myLabel];

    [myLabel release];

    return cell;
}

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

    NSString *text = [[person.updates objectAtIndex:indexPath.row] valueForKey:@"text"];
    UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
    CGSize withinSize = CGSizeMake(tableView.frame.size.width, 1000);
    CGSize size = [text sizeWithFont:font constrainedToSize:withinSize lineBreakMode:UILineBreakModeWordWrap];

    return size.height + 20;    
}

Also, what am I missing that makes the labels appear longer than the table cell? alt text

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Jason
  • 17,276
  • 23
  • 73
  • 114

3 Answers3

15

Tweetero provides an example of this in MessageListController.m. The code there renders the following screen:

(Pic is taken from Mashable).

The basic implementation outline:

  1. When constructing a UITableViewCell, create and add a UILabel as a subview in the manner shown in tableviewCellWithReuseIdentifier:. Look for the creation of TEXT_TAG label.

  2. when enriching the UITableViewCell with views, ensure that you format label properly, as is done in configureCell:forIndexPath, similarly look for the label tag TEXT_TAG.

  3. Return the appropriate height for each cell, as is done in tableView:heightForRowAtIndexPath.

Community
  • 1
  • 1
notnoop
  • 58,763
  • 21
  • 123
  • 144
2
myLabel.numberOfLines = 2;

Check the docs for full info on how to use this property.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • the problem is that it won't always be a specific number, it will change for each row – Jason Aug 05 '09 at 14:36
  • The numberOfLines property sets the **maximum** number of lines. Set it to a high value. (And, as Rob said, check the docs.) – Nikolai Ruhe Aug 05 '09 at 14:37
  • 2
    You also have to set the myLabel.lineBrakeMode to UILineBreakModeWordWrap. – Nikolai Ruhe Aug 05 '09 at 14:39
  • Setting it to 0 means "no maximum." @Nikolai's right about lineBreakMode; I had in my head that WordWrap was the default for UILabel, but it's not. – Rob Napier Aug 05 '09 at 14:48
0
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return theSizeYouWantYourCellToBe;
}
Thizzer
  • 16,153
  • 28
  • 98
  • 139