Проблема с перекрывающимися изображениями в ячейках UITableView - PullRequest
1 голос
/ 28 мая 2011

У меня есть 2 таблицы в coredata sqlite Painter и Picture. С отношениями один ко многим. В таблице "picture" у меня есть строковый атрибут pictureName. Храню картинки (153) на диске Этот код я добавляю imageViews в ячейки:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    self.tableView.transform = CGAffineTransformMakeRotation( -M_PI/2 );
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setFrame:CGRectMake(0, 156, 1024, 449)];
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}
#pragma mark - UITableView Delegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[fetchedResultsController fetchedObjects] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    Painter *painter = [[fetchedResultsController fetchedObjects] objectAtIndex:section];
    //NSLog(@"%i", [painter.pictures count]);
    return [painter.pictures count];
    //return 152;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    Painter *painter = [[fetchedResultsController fetchedObjects] objectAtIndex:indexPath.section];
    Picture *picture = [[painter.pictures allObjects] objectAtIndex:indexPath.row];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@s.jpg", picture.imgName]]];
    NSLog(@"add image %@s.jpg to sector:%i row:%i", picture.imgName, indexPath.section, indexPath.row);
    imageView.transform = CGAffineTransformMakeRotation( M_PI/2 );
    [cell addSubview:imageView];
    [imageView release];
}

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

    UITableViewCell *cell = [tableViewCurrent dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}
- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 300.0;
}

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
}


#pragma mark - Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController
{
    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    }

    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Painter" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];


    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Main"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];

    return fetchedResultsController;
}

` И у меня проблема: много фото в каждой клетке http://ge.tt/9QX5lc4?c (выберите кнопку просмотра) Почему?

Ответы [ 2 ]

2 голосов
/ 28 мая 2011

Следующий код вызывает у вас проблему:

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableViewCurrent dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;

Вы в основном кэшируете ячейку при первом ее создании и повторно используете ее при последующих вызовах tableView:cellForRowAtIndexPath: Если выЕсли вы не хотите, чтобы это кэшировалось, вам нужно каждый раз создавать новую ячейку.

UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;

Это должно решить вашу проблему.Существуют более сложные способы обработки ячеек, такие как кеширование и непосредственное управление его подпредставлениями вместо того, чтобы каждый раз воссоздавать его.Что-то стоит иметь в виду, когда вы продолжаете работать над своим кодом.

2 голосов
/ 28 мая 2011

Клетки используются повторно. Каждый раз, когда вы настраиваете ячейку, вы добавляете изображение в качестве подпредставления. Со временем они накапливаются и дают эффект, который вы видите. Вы должны проверить, существует ли изображение, и назначить ему изображение или сначала очистить ячейку, а затем настроить его с помощью изображения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...