xcode CollectionViewController scrollToItemAtIndexPath not working

前端 未结 9 891
故里飘歌
故里飘歌 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:52

    This is based on @Womble's answer, all credit goes to them:

    The method viewDidLayoutSubviews() gets called repeatedly. For me (iOS 11.2) the first time it gets called the collectionView.contentSize is {0,0}. The second time, the contentSize is correct. Therefore, I had to add a check for this:

    var needsDelayedScrolling = false
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.needsDelayedScrolling = true
        // ...
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if self.needsDelayedScrolling && collectionView.contentSize.width > 0 {
            self.needsDelayedScrolling = false
            self.collectionView!.scrollToItem(at: someIndexPath,
                    at: .centeredVertically,
                    animated: false)
            }
        }
    }
    

    After adding that extra && collectionView.contentSize.width > 0 it works beautifully.

提交回复
热议问题