xcode CollectionViewController scrollToItemAtIndexPath not working

前端 未结 9 823
故里飘歌
故里飘歌 2021-02-01 03:06

I have created a CollectionView Control and filled it with images. Now I want to scroll to item at a particular index on start. I have tried out scrollToItemA

9条回答
  •  滥情空心
    2021-02-01 03:33

    Whether it's a bug or a feature, UIKit throws this error whenever scrollToItemAtIndexPath:atScrollPosition:Animated is called before UICollectionView has laid out its subviews.

    As a workaround, move your scrolling invocation to a place in the view controller lifecycle where you're sure it has already computed its layout, like so:

    @implementation CollectionViewControllerSubclass
    
    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        // scrolling here doesn't work (results in your assertion failure)
    }
    
    - (void)viewDidLayoutSubviews
    {
        [super viewDidLayoutSubviews];
    
        NSIndexPath *indexPath = // compute some index path
    
        // scrolling here does work
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                            animated:YES];
    }
    
    @end
    

    At the very least, the error message should probably be more helpful. I've opened a rdar://13416281; please dupe.

提交回复
热议问题