agentfll
agentfll

Reputation: 858

Make UITableViewCell expand when text exceeds space

I have a UITableViewCell and it is UITableViewCellStyleDefault. When I try to put text longer than the UITableViewCell, it truncates it. How do I make the cell expand to accommodate this text?

Upvotes: 2

Views: 2245

Answers (3)

Jason G
Jason G

Reputation: 51

I haven't tried to do exactly what you're trying to do, but it would probably go something like this:

You need to change the size of a view depending on the length of the text string inside it.

The table view delegate (your view controller) should implement

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message *msg = (Message *)[messages objectAtIndex:indexPath.row];
    CGSize size = [[msg text] sizeWithFont:[UIFont fontWithName:@"Helvetica" size:kLabelFontSize]
                         constrainedToSize:CGSizeMake(220.0f, 480.0f)
                             lineBreakMode:UILineBreakModeTailTruncation];
    CGFloat minHeight = 20.0f;
    CGFloat height = size.height > minHeight ? size.height : minHeight;
    return height;
}

which tells the view how tall to make each row.

You're going to need to need to also resize the UITableViewCell label's frame similarly.

Upvotes: 2

jkeesh
jkeesh

Reputation: 3339

I think all of the cells need to be the same height and width. You can change the height of the UITableViewCells using the tableView's rowHeight property.

For example, if you subclass UITableViewController

self.tableView.rowHeight = 100;

Another option is to add a custom UILabel as a subview of the cells contentView like shown earlier.

Upvotes: 0

Mihir Mehta
Mihir Mehta

Reputation: 13843

You can not expand cell's width more than iphone's screen... What you can do is 1> make font smaller 2> make your text multiple lines

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    CGRect contentRect = CGRectMake(80.0, 0.0, 240, 40);
    UILabel *textView = [[UILabel alloc] initWithFrame:contentRect];

    textView.text = mytext;
    textView.numberOfLines = 2;
    textView.textColor = [UIColor grayColor];
    textView.font = [UIFont systemFontOfSize:12];
        [cell.contentView addSubview:textView];
    [textView release];

Upvotes: 1

Related Questions