我如何在没有自定义单元格的UITableViewCell中包装文本

时间:2020-03-06 14:41:10  来源:igfitidea点击:

这是在iPhone 0S 2.0上。 2.1的答案也很好,尽管我不知道有关表的任何差异。

感觉好像应该可以在不创建自定义单元的情况下自动换行,因为UITableViewCell默认包含UILabel。我知道如果创建自定义单元可以使其工作,但这不是我要达到的目的,我想了解为什么我当前的方法不起作用。

我发现标签是按需创建的(由于单元格支持文本和图像访问,因此它直到需要时才创建数据视图),因此如果执行以下操作:

cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];

然后我得到一个有效的标签,但是在该标签上设置numberOfLines(和lineBreakMode)不起作用,我仍然得到单行文本。 UILabel中有足够的高度用于显示文本,我只是在heightForRowAtIndexPath中返回一个很大的高度值。

解决方案

我认为我们不能操纵基本的UITableViewCell的私有UILabel来做到这一点。我们可以自己向单元格添加一个新的UILabel,并使用带有numberToFit的numberOfLines和适当的大小。就像是:

UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];
label.numberOfLines = <...an appriate number of lines...>
label.text = <...your text...>
[label sizeToFit];
[cell addSubview:label];
[label release];

这是一种更简单的方法,对我有用:

cellForRowAtIndexPath:函数内部。首次创建单元格时:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

我们会注意到,我将标签的行数设置为0。这使它可以根据需要使用任意多的行。

下一部分是指定UITableViewCell的大小,请在heightForRowAtIndexPath函数中执行以下操作:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height + 20;
}

我在返回的单元格高度上增加了20,因为我喜欢在文本周围留一些缓冲。

我认为这是一个更好,更短的解决方案。只需通过指定sizeToFit格式化单元格的'UILabel'(textLabel)即可自动计算高度,一切就可以了。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

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

    // Configure the cell...
    cell.textLabel.text = @"Whatever text you want to put here is ok";
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    [cell.textLabel sizeToFit];

    return cell;
}