HaloZero
HaloZero

Reputation: 485

Autolayout and Collection View Issue

So the basic issue is that when I click the cell, it should go to cell index 1 in the new view controller, but when you have autolayout on. The collectionview content offset change goes away and it's reset. Turn it off, works fine. Autolayout is somehow causing content offset to reset but I'm not sure why or how to resolve this.

Code available here.

https://github.com/HaloZero/AutolayoutCollectionViewIssue

Upvotes: 1

Views: 925

Answers (2)

Valent Richie
Valent Richie

Reputation: 5226

It is not that auto-layout is resetting the content offset, but the subviews have not been positioned when you try to snap the cell.

With auto-layout, the subviews are positioned a bit later (in which the viewWillAppear is called first). Try to use viewDidLayoutSubviews instead for your snapping of the cell:

From the documentation for viewDidLayoutSubviews:

Notifies the view controller that its view just laid out its subviews.

So after all the constraints have been calculated and your subviews have been laid, you can call the snapping method.

- (void)viewDidLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self snapToCellAtIndex:1 withAnimation:NO];
}

Upvotes: 0

Prince Kumar Sharma
Prince Kumar Sharma

Reputation: 12641

use you code as :--

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self performSelectorOnMainThread:@selector(doyouwork) withObject:nil waitUntilDone:NO];
}

-(void)doyouwork
{
    [self snapToCellAtIndex:1 withAnimation:NO];
}

- (void) snapToCellAtIndex:(NSInteger)index withAnimation:(BOOL) animated
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:index inSection:0];
    [self.collectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionLeft animated:animated];
}

working for my side.

Upvotes: 1

Related Questions