Question

The best way to demonstrate my problem is with the video below:

http://foffer.dk/collectionview.mp4

As you can see, my collectionView doesn't update it's layout to correctly display the items until I start scrolling. I'm using a separate collectionViewFlowLayout model. Here is my code:

CollectionViewFlowLayout.m:

@implementation CollectionViewFlowLayout

- (void)prepareLayout {

    CGFloat halfWidth = self.collectionView.bounds.size.width / 2;
    CGFloat halfHeight = self.collectionView.bounds.size.height / 2;


    self.itemSize = CGSizeMake(halfWidth, halfHeight);
    self.minimumInteritemSpacing = 0;
    self.minimumLineSpacing = 0;

}


// indicate that we want to redraw as we scroll
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}

@end

my PhotosCollectionViewController (I've left out the standart collectionView stuff as I didn't think it is important to this issue, let me know if it is and I will post it):

-(instancetype)init {
    UICollectionViewFlowLayout *layout = [[CollectionViewFlowLayout alloc] init];


    return (self = [super initWithCollectionViewLayout:layout]);
}

-(void) viewDidLoad{
    [super viewDidLoad];


    [self.collectionView registerClass:[FOFPhotoCell class] forCellWithReuseIdentifier:@"photo"];
    self.collectionView.backgroundColor = [UIColor whiteColor];


    CGFloat bottomLayoutGuide =  self.tabBarController.tabBar.frame.size.height;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, bottomLayoutGuide, 0);

}

-(BOOL)shouldAutorotate{
    return YES;
}

Do I need to call invalidateLayout somewhere? I can't seem to figure out where to implement that method. [self.collectionView invalidateLayout] doesn't work.

Could someone get me on the right track here?

Thanks in advance Chris

Was it helpful?

Solution

So, it turns out I had it set up all wrong. As this article from apple says:

Before you start building custom layouts, consider whether doing so is really necessary.

The UICollectionViewFlowLayout class provides a significant amount of behavior that has already been optimized for efficiency and that can be adapted in several ways to achieve many different types of standard layouts. The only times to consider implementing a custom layout are in the following situations:

The layout you want looks nothing like a grid or a line-based breaking layout (a layout in which items are placed into a row until it’s full, then continue on to the next line until all items are placed) or necessitates scrolling in more than one direction.

You want to change all of the cell positions frequently enough that it would be more work to modify the existing flow layout than to create a custom layout.

And my layout config is really simple. So I was overcomplicating it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top