UItableviewcontroller SizeToFit 不适用于 UILabel 字段

UItableviewcontroller SizeToFit not working on UILabel field

您好,我在我的 UILabel 字段上使用 sizetofit,当我加载 tableview 控制器时它工作正常,但是当我上下滚动时开始切割字母并换行到另一行。这是我在 CellForRowAtIndexPath 中使用的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"subjectCell" forIndexPath:indexPath];

    // Configure the cell...

    // Load and display subject photo image
    UIImageView *subjectImageView = (UIImageView *)[cell viewWithTag:200];
    subjectImageView.image = [UIImage imageNamed:subjectImages[indexPath.row]];


    // Load and display subject label
    UILabel *subjectLabel = (UILabel *)[cell viewWithTag:201];
    subjectLabel.text = [subjectItems objectAtIndex:indexPath.row];
    [subjectLabel sizeToFit];// call this to fit size of the label according to text



    return cell;
}

这是我最初加载的 tableviewcontroller 的屏幕截图:

这里上下滚动后可以看到描述被删减了

感谢您为解决此问题提供的任何帮助。

干杯

卡森

sizeToFit 用于 UILabel 可能会在 UITableView 中导致像这样的混乱,重复使用单元格。我能想到的解决方案之一是在调用 sizeToFit 之前为标签宽度设置框架的宽度,并且每次将文本分配给标签时都必须这样做。它应该看起来像这样:

CGRect frame = subjectLabel.frame;
frame.size.width = 100.0; //try to adjust this value 
subjectLabel.frame = frame;
[subjectLabel sizeToFit];