0

我正在尝试调整表格单元格中 UILabel 的高度。在我的情况下,表是动态的,我使用两个 UILabel 对其进行了自定义。该表将准确显示 11 个项目,但其中两个单元格需要容纳多行文本 UILabel。我有选择地增加两个单元格的高度,如下所示:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 3 || indexPath.row == 10)
         return 100;
    else
        return 46;
}

但我还需要只为这两个单元格增加 UILabel 的高度。我尝试使用以下代码(也尝试了该站点的其他一些示例)。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


    // Configure the cell...
    UILabel *DetailLabel = (UILabel *)[cell.contentView viewWithTag:10];
    UILabel *DetailText = (UILabel *)[cell.contentView viewWithTag:20];

    if(indexPath.row == 3 || indexPath.row ==10){
        [DetailText setText:[self.EmployerViewText objectAtIndex:[indexPath row]]];

        DetailText.lineBreakMode = NSLineBreakByWordWrapping;
        DetailText.font = [UIFont systemFontOfSize:17.0f];
        DetailText.numberOfLines = 0;
        DetailText.frame = CGRectMake(0, 0, 317, 80);
        [DetailText sizeToFit];

    }else{

        [DetailText setText:[self.EmployerViewText objectAtIndex:[indexPath row]]];
    }

    [DetailLabel setText:[self.EmployerViewLabel objectAtIndex:[indexPath row]]];

   return cell;
}

不幸的是,UILable 的大小保持不变。谁能指出我做错了什么?

4

2 回答 2

1

问题是当您更改 DetailText 中的文本时,您不会再次调用 [DetailText sizeToFit]。

    DetailText = [[UILabel alloc]initWithFrame:CGRectMake(60, 200, 100, 30)];
    DetailText.backgroundColor = [UIColor orangeColor];

    DetailText.lineBreakMode = NSLineBreakByWordWrapping;
    DetailText.font = [UIFont systemFontOfSize:17.0f];
    DetailText.numberOfLines = 0; // Here is the key
    DetailText.text = @"test message test message test message test message test message test message";
    DetailText.frame = CGRectMake(100, 0, 100, 80);
    [DetailText sizeToFit];

更改文本后:

    DetailText.text = @"this is the modified text";
    [DetailText sizeToFit];

我尝试了这段代码并调整了它的大小。

于 2013-10-19T10:31:16.547 回答
0

来自 UILabel.h:

// this determines the number of lines to draw and what to do when sizeToFit is called. default value is 1 (single line). A value of 0 means no limit
// if the height of the text reaches the # of lines or the height of the view is less than the # of lines allowed, the text will be
// truncated using the line break mode.

@property(nonatomic) NSInteger numberOfLines;

只允许多行 UILabel:

    ...
    [DetailText setText:[self.EmployerViewText objectAtIndex:[indexPath row]]];

    DetailText.lineBreakMode = NSLineBreakByWordWrapping;
    DetailText.font = [UIFont systemFontOfSize:17.0f];
    DetailText.numberOfLines = 0; // Here is the key

    DetailText.frame = CGRectMake(0, 0, 317, 80);
    [DetailText sizeToFit];
    ...

对于其他情况,您可能希望将 numberOfLines 设置为 1。

于 2013-10-19T10:09:35.010 回答