简体   繁体   中英

Change the height dynamically on UITableViewCell's based on 1 label?

How can I scale UITableViewCells based on the amount of content in them? In my cells I use 3 labels which represent a forum. The labels are named "alias", "date", and "comments". The third label comments, can be any number of rows. Therefore, my cells need to become dynamically depending on the amount of text(size) it is in the "comments" label. Below is my relevant code:

- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ForumthreadCell";
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

Feedback *item = [self.items objectAtIndex:indexPath.row];

UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];

[aliasLabel setText:item.alias];
[commentLabel setText:item.comment];
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]];

commentLabel.numberOfLines = 0;
[commentLabel sizeToFit];

return cell;
}

In this method am I supposed to set the tableViewCell's height depending on commentLabel height.. The only problem is I am not sure how to do it?

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

    return ????;
    //return [indexPath row] + 50;

}

return ????;
}

I need help from someone that tries to take a look at my code and give examples how I can make this work. After all, its only 1 label.... I have already looked at several tutorials but not been able to make it work... Thanx for your time and help. This is an old screen with some old code. This is more or less what the forum looks like now: http://tinypic.com/view.php?pic=16h7me9&s=6

What you need is a way to calculate the size of a text rendered with a specific font. Luckily, UIKit provides you with exactly this via the various sizeWithFont: methods in NSString UIKit Additions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM