1

重用我的自定义 UITableViewCell 时,不会为当前单元格重置所有数据。为特定的 UILabel 插入来自重用单元的数据。

我有一个菜肴的表格视图。菜品有评论。我想在 tableviewcell 中显示每道菜的评论。根据有多少评论,我只在每个单元格中制作那么多评论标签。然而,当一个单元格被重用时,错误的评论——来自不同盘子的评论——就会出现。

我正在使用 CoreData,一个 Dish 有很多评论,假设我只想显示前两条评论。

我在 IB 中创建了两个高度和宽度为零的 UILabel,以便它调整每个评论的长度。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath    *)indexPath
{
    DishCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DishCell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{ ...I put all of the Dishes in a NSFetchedResultsController instance so *dish is a NSManagedObject that has many comments

      NSSet *commentsSet = dish.comments;
      NSSortDescriptor *sortByDate = [[NSSortDescriptor alloc]initWithKey:@"date"  ascending:YES];
      NSArray *commentArray = [commentsSet sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortByDate]];

     if (commentsSet.count< 1) {
        dishCell.comment1label.text = @"";
        dishCell.comment2label.text = @"";
     }else {

    Comment *comment = [commentArray objectAtIndex:0];

    NSString *commenterName = comment.displayName;
    NSString *commentString = comment.commentText;
    NSString *text = [NSString stringWithFormat:@"%@: %@", commenterName, commentString];

    CGSize comment1Size = [text sizeWithFont:[UIFont systemFontOfSize:10.0f] constrainedToSize:CGSizeMake(constraint.width - dishCell.commentBubble.frame.size.width + 4, constraint.height) lineBreakMode:UILineBreakModeWordWrap];

    //Ignore this setFrame - it works
    [dishCell.comment1label setFrame:CGRectMake(32, faveIconYpos - 2 + dishCell.favIcon.frame.size.height, 298 - dishCell.commentBubble.frame.size.width, comment1Size.height + 2)];

    dishCell.text = text;

    if (commentsSet.count > 1) {
        Comment *comment2 = [commentArray objectAtIndex:1];
        [dishCell.comment2label setTextColor:[UIColor whiteColor]];
        [dishCell.comment2label setFont:[UIFont systemFontOfSize:12.0]];

        NSString *text2 = [NSString stringWithFormat:@"%@: %@", comment2.displayName, comment2.commentText];

        CGSize comment2Size = [text2 sizeWithFont:[UIFont systemFontOfSize:10.0f] constrainedToSize:CGSizeMake(constraint.width - dishCell.commentBubble.frame.size.width + 4, constraint.height) lineBreakMode:UILineBreakModeWordWrap];
        [dishCell.comment2label setFrame:CGRectMake(32, faveIconYpos + dishCell.favIcon.frame.size.height + dishCell.testcom.frame.size.height - 2, 298 - dishCell.commentBubble.frame.size.width, comment2Size.height + 2)];
        dishCell.comment2label.text = text2; 
    }

我已经解析了一些代码,但主要的是来自另一个单元格的数据被插入到我的标签中。为什么会这样?

4

0 回答 0