Simple UICollectionView to show images behaves odd: Some Images are displayed correct, some at wrong position, some missing at all

后端 未结 1 536
野趣味
野趣味 2021-02-12 20:32

I want to show images in a grid on iPhone using a UICollectionView, showing 3 images a row. For a \"dead simple test\" (as I thought), I\'ve added 15 JPG images to my project, s

相关标签:
1条回答
  • 2021-02-12 20:40

    In the meantime, I've found the solution. It was actually a very subtle error in the implementation of my UICollectionViewCell subclass AlbumCoverCell.

    The problem is that I've set the frame of the cell instance as the frame of the UIImageView subview instead of passing the bounds property of the cell's contentView!

    Here is the fix:

    @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
    
    0 讨论(0)
提交回复
热议问题