Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a variable sized UITableViewCell?

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

like image 756
Jason Avatar asked Aug 05 '09 14:08

Jason


People also ask

How do you create a dynamic height table in a cell?

Image view without an image selected has no intrinsic content size, hence we need to set an explicit height constraint for it. The key to achieve dynamic height table view cell is to let Auto Layout know how to calculate the height of the cell.

How do you find the height of a cell?

Set a row to a specific height Select the row or rows that you want to change. On the Home tab, in the Cells group, click Format. Under Cell Size, click Row Height. In the Row height box, type the value that you want, and then click OK.

What is Uitableview in Swift?

A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+


2 Answers

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.

like image 50
notnoop Avatar answered Oct 19 '22 10:10

notnoop


myLabel.numberOfLines = 2;

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

like image 30
Rob Napier Avatar answered Oct 19 '22 09:10

Rob Napier