UICollectionView automatically scroll to bottom when screen loads

后端 未结 9 2090
Happy的楠姐
Happy的楠姐 2021-02-05 02:44

I\'m trying to figure out how to scroll all the way to the bottom of a UICollectionView when the screen first loads. I\'m able to scroll to the bottom when the status bar is tou

9条回答
  •  盖世英雄少女心
    2021-02-05 02:54

    The issue is likely that even if your collection view is on screen, it might not have the actual contentSize.

    If you scroll in viewDidAppear, you will have a contentSize, but your scollectionview will briefly show content before scrolling.

    And the problem with viewDidLayoutSubviews is that it is called multiple times, so you then need to add an ugly boolean to limit scrolling.

    The best solution i've found is to force layout in view will appear.

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // force layout before scrolling to most recent
        collectionView.layoutIfNeeded()
        // now you can scroll however you want
        // e.g. scroll to the right
        let offset = collectionView.contentSize.width - collectionView.bounds.size.width
        collectionView.setContentOffSet(CGPoint(x: offset, y: 0), animated: animated)
    }
    

提交回复
热议问题