如何根据Stringlength更改TableViewCell的rowHeight

时间:2010-02-24 09:46:01

标签: iphone cocoa-touch uikit uitableview

我有一个包含不同条目的表,每个条目都有不同的长度。每行的高度应该适合,因此它可以显示整个字符串。

我使用以下代码:

//... cellForRowAtIndexPath
if (row == 0) {

    cell = [tableView dequeueReusableCellWithIdentifier:@"affCell"];
    //if (!cell) {
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"affCell"]autorelease];
     cell.accessoryType = UITableViewCellAccessoryNone;
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
     cell.autoresizingMask = UIViewAutoresizingFlexibleHeight;

     affL = [[UILabel alloc] initWithFrame:CGRectZero];
     affL.textAlignment = UITextAlignmentLeft;
     affL.autoresizingMask = UIViewAutoresizingFlexibleHeight;
     [cell.contentView addSubview:affL];
    //}
    //declaration label
    affL.text = [fDictionary objectForKey:@"aff"];
    affL.numberOfLines = 0;
    [affL sizeToFit];
    affL.frame = CGRectMake(15.0, 10.0, 220.0, affL.frame.size.height);
    CGFloat affLH = affL.frame.size.height;
    [tableView setRowHeight:affLH+30];

我也用

//... heightForRowAtIndexPath

return affL.frame.size.height;

如何解决此问题?

2 个答案:

答案 0 :(得分:0)

在-heightForRowAtIndexPath中,您必须以所需的字体大小测量字符串(使用类似 - sizeWithFont:constrainedToSize:lineBreakMode :)并返回所需的高度。

答案 1 :(得分:0)

我想我不需要在单元格中添加标签,因为单元格只包含一个字符串。

因此我将代码更改为:

//... heightForRow...

NSString *myText = [myDictionary objectForKey:@"affirmation"];

return [myText sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:
CGSizeMake(220.0, CGFLOAT_MAX) /* 220 = width of Cell */ lineBreakMode:UILineBreakModeWordWrap].height;

//... cellForRow...

cell = [tableView dequeueReusableCellWithIdentifier:@"affirmationCell"];
if (cell == nil) 
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"affirmationCell"]autorelease];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
}

cell.textLabel.text = [myDictionary objectForKey:@"myAff"];

return cell;

但它不起作用。出了什么问题?