1

我正在尝试创建一个表格视图,其中单元格的高度是动态的。

到目前为止,我设法根据我在里面添加的自定义 UILabel 设置单元格的高度。

使用常规的 cell.textLabel 可以正常工作,但是当我使用自己的标签时出现问题。我只看到一半的标签,但是当我上下滚动时,有时标签会延伸并显示所有文本......您可以看到标签应该在图像中结束的位置。

图片

这是里面的文字cellForRowAtIndexPath

static NSString *CellIdentifier = @"Cell";

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

// Configure the cell.
Car *carForCell = [cars objectAtIndex:indexPath.row];

UILabel *nameLabel = [[UILabel alloc] init];
nameLabel = (UILabel *)[cell viewWithTag:100];
nameLabel.numberOfLines = 0;
nameLabel.text = carForCell.directions;
[nameLabel sizeToFit];

[nameLabel setBackgroundColor:[UIColor greenColor]];


return cell;
4

3 回答 3

1

除非您发布的代码中有拼写错误,否则您似乎根本没有将标签添加到单元格中。您似乎每次都在创建一个新标签,然后将nameLabel指针的内容替换为单元格的视图(始终为 nil)。

尝试先做这样的事情,然后看看它的样子:

static NSString *CellIdentifier = @"Cell";

UILabel *nameLabel;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

    nameLabel = [[UILabel alloc] init];
    nameLabel.tag = 100;

    nameLabel.numberOfLines = 0;
    [nameLabel setBackgroundColor:[UIColor greenColor]];

    [cell.contentView addSubview:nameLabel];
}
else {
     nameLabel = (UILabel *)[cell viewWithTag:100];
}

// Configure the cell.
Car *carForCell = [cars objectAtIndex:indexPath.row];

nameLabel.text = carForCell.directions;
[nameLabel sizeToFit];

return cell;

您还需要使用tableView:heightForRowAtIndexPath:委托方法告诉 tableView 每个单元格的大小。这将意味着Car再次获取相关对象并使用计算高度sizeWithFont:sizeWithFont:forWidth:lineBreakMode:

于 2013-02-08T18:10:45.627 回答
0

你如何设置单元格的高度?它应该在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

于 2013-02-08T18:03:19.747 回答
0

您应该通过以下方法计算并返回 UITableViewCell 的高度:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

在这里,您应该初步计算您的细胞应该有多高。

例如:

CGSize textSize = [myString sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(320, 9999)];
return textSize.height;
于 2013-02-08T18:04:45.633 回答