【问题标题】:How can I create a variable sized UITableViewCell?如何创建可变大小的 UITableViewCell?
【发布时间】:2010-11-17 01:03:29
【问题描述】:

我似乎无法让文本实际跨越多行。高度看起来是正确的。我错过了什么?

- (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;    
}

另外,我缺少什么使标签看起来比表格单元格长?

【问题讨论】:

    标签: iphone objective-c cocoa-touch uitableview cs193p


    【解决方案1】:
    myLabel.numberOfLines = 2;
    

    查看docs 以获取有关如何使用此属性的完整信息。

    【讨论】:

    • 问题是它并不总是一个特定的数字,它会随着每一行而改变
    • numberOfLines 属性设置最大行数。将其设置为高值。 (而且,正如 Rob 所说,请查看文档。)
    • 您还必须将 myLabel.lineBrakeMode 设置为 UILineBreakModeWordWrap。
    • 将其设置为 0 意味着“没有最大值”。 @Nikolai 关于 lineBreakMode 的权利;在我的脑海中,WordWrap 是 UILabel 的默认设置,但事实并非如此。
    【解决方案2】:

    Tweetero 在MessageListController.m 中提供了一个示例。那里的代码呈现以下屏幕:

    (图片取自Mashable)。

    基本实现大纲:

    1. 在构造UITableViewCell 时,以tableviewCellWithReuseIdentifier: 中所示的方式创建并添加UILabel 作为子视图。寻找TEXT_TAG标签的创建。

    2. 当使用视图丰富UITableViewCell 时,确保您正确格式化标签,就像在configureCell:forIndexPath 中所做的那样,同样查找标签标签TEXT_TAG。

    3. 为每个单元格返回适当的高度,就像在 tableView:heightForRowAtIndexPath 中所做的那样。

    【讨论】:

      【解决方案3】:
      - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
      {
          return theSizeYouWantYourCellToBe;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-04-09
        • 2019-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        相关资源
        最近更新 更多