0

我正在将自定义单元格加载到表格视图中,并注意到我的单元格没有被正确重用。我正在使用 NSFetchedResultsController 从核心数据中提取结果。

我正在从笔尖加载单元格。单元标识符在界面生成器中设置。这些单元格似乎被重复使用,因为我没有在每次滚动表格时创建一个新单元格。但是,单元格上的数据未正确显示。

// BeerCell.h
@interface BeerCell : UITableViewCell

@property (nonatomic, strong) IBOutlet UIImageView *beerImage;
@property (nonatomic, strong) IBOutlet UILabel *displayBeerName;
@property (nonatomic, strong) IBOutlet UILabel *displayBeerType;

@end

// BeerCell.m
@implementation BeerCell

@synthesize beerImage;
@synthesize displayBeerName;
@synthesize displayBeerType;

@end

 // Code where i'm setting up the cells for the tableView

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

    BeerCell *cell = (BeerCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BeerCell" owner:self options:nil];

        for (id currentObject in topLevelObjects){

            if ([currentObject isKindOfClass:[UITableViewCell class]]){
                cell =  (BeerCell *) currentObject;
                break;
            }
        }

        [self configureCell:cell atIndexPath:indexPath];

    }        

    return cell;
}

- (void)configureCell:(BeerCell *)cell 
          atIndexPath:(NSIndexPath *)indexPath 
{
    Beer *beer = (Beer *) [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.displayBeerName.text = beer.name;
}
4

1 回答 1

1

在 if 块之外调用 configureCell 函数。

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

    BeerCell *cell = (BeerCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BeerCell" owner:self options:nil];

        for (id currentObject in topLevelObjects){

            if ([currentObject isKindOfClass:[UITableViewCell class]]){
                cell =  (BeerCell *) currentObject;
                break;
            }
        }
    }        
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}
于 2012-07-16T13:42:47.820 回答