Подтвердить что ты не робот

Простой UICollectionView для отображения изображений ведет себя нечетно: некоторые изображения отображаются правильно, некоторые в неправильном положении, некоторые отсутствуют вообще

Я хочу показывать изображения в сетке на iPhone с помощью UICollectionView, показывая 3 изображения строки. Для "мертвого простого теста" (как я думал), я добавил 15 изображений JPG в свой проект, чтобы они были в моем комплекте, и я могу загрузить их просто через [UIImage imageNamed:...].

Я думаю, что я сделал все правильно (настройка и регистрация подкласса UICollectionViewCell, использование методов протокола UICollectionViewDataSource), однако UICollectionView ведет себя очень странно:

Он отображает только несколько изображений в следующем шаблоне: Первая строка показывает изображение 1 и 3, вторая строка пуста, следующая строка, как первая, снова (изображение 1 и 3 отображается правильно), четвертая строка и т.д....

Если я нажму кнопку в моем NavBar, которая запускает [self.collectionView reloadData], случайные ячейки появляются или исчезают. Что меня заводит, так это то, что это не только проблема с изображениями или нет. Иногда изображения также меняются между ячейками, т.е. Они появляются для indexPath, они определенно не подключены!

Вот мой код для ячейки:

@interface AlbumCoverCell : UICollectionViewCell
@property (nonatomic, retain) IBOutlet UIImageView *imageView;
@end

@implementation AlbumCoverCell
@synthesize imageView = _imageView;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _imageView = [[UIImageView alloc] initWithFrame:frame];
        [self.contentView addSubview:_imageView];
    }
    return self;
}

- (void)dealloc
{
    [_imageView release];
    [super dealloc];
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    self.imageView.image = nil;
}
@end

Часть кода для моего подкласса UICollectionViewController, где "imageNames" - это NSArray, содержащий все имена файлов jpg:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.collectionView registerClass:[AlbumCoverCell class] forCellWithReuseIdentifier:kAlbumCellID];
}

#pragma mark - UICollectionViewDataSource Protocol methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.imageNames count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AlbumCoverCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kAlbumCellID forIndexPath:indexPath];
    NSString *imageName = [self.imageNames objectAtIndex:indexPath.row];
    NSLog(@"CV setting image for row %d from file in bundle with name '%@'", indexPath.row, imageName);
    cell.imageView.image = [UIImage imageNamed:imageName];

    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout Protocol methods
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    return CGSizeMake(100, 100);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

Из инструкции NSLog в cellForItemAtIndexPath: я вижу, что метод вызывается для всех ячеек (а не только для одного) и что сопоставление между indexPath.row и именем файла верное.

Кто-нибудь знает, что может вызвать это странное поведение?

4b9b3361

Ответ 1

Тем временем я нашел решение. Это была очень тонкая ошибка в реализации моего подкласса UICollectionViewCell AlbumCoverCell.

Проблема заключается в том, что я установил кадр экземпляра ячейки как кадр подвью UIImageView вместо передачи свойства bounds ячейки contentView!

Вот исправление:

@implementation AlbumCoverCell
@synthesize imageView = _imageView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // WRONG:
        // _imageView = [[UIImageView alloc] initWithFrame:frame];

        // RIGHT:
        _imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
        [self.contentView addSubview:_imageView];
    }
    return self;
}


- (void)prepareForReuse
{
    [super prepareForReuse];

    // reset image property of imageView for reuse
    self.imageView.image = nil;

    // update frame position of subviews
    self.imageView.frame = self.contentView.bounds;
}

...

@end