UItableviewcontroller SizeToFit不适用于UILabel字段

时间:2015-09-05 15:39:00

标签: ios objective-c uitableview sizetofit

您好我在我的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最初加载的屏幕截图:

enter image description here

在向上和向下滚动之后,您可以看到描述已被删除

enter image description here

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

干杯

卡森

1 个答案:

答案 0 :(得分:1)

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

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