【问题标题】:How to change rowHeight of a TableViewCell depending on Stringlength如何根据 Stringlength 更改 TableViewCell 的 rowHeight
【发布时间】:2010-02-24 09:46:01
【问题描述】:

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

我使用以下代码:

//... 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;

我该如何解决这个问题?

【问题讨论】:

    标签: iphone cocoa-touch uikit uitableview


    【解决方案1】:

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

    【讨论】:

    • 好的,仔细看看.. 你仔细检查你的 -dequeueReusableCellWithIdentifier 是否为 nil,对吧?如果它不是 nil 你想重用它以获得更好的性能。它已经包含一个 UILabel。如果每个单元格的高度不同,您可能不想在每次调用 -cellForRowAtIndexPath 时都调用 [tableView setRowHeight:] 。在 - heightForRowAtIndexPath 返回 UILabel 的高度可以工作,否则尝试 [myString sizeWithFont: affL.font constrainedToSize:CGSizeMake(affL.frame.size.width, CGFLOAT_MAX)]
    【解决方案2】:

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

    因此我将代码更改为:

    //... 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;
    

    但它不起作用。怎么了?

    【讨论】:

    • 我修好了!必须添加一个默认值到高度返回 [...].height + 44.0;
    • return 语句运行后,您将没有任何东西。函数或方法返回时停止执行。
    猜你喜欢
    • 2019-09-04
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多