UICollectionView automatically scroll to bottom when screen loads

后端 未结 9 2099
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 03:03

    Consider if you can use performBatchUpdates like this:

    private func reloadAndScrollToItem(at index: Int, animated: Bool) {
        collectionView.reloadData()
        collectionView.performBatchUpdates({
            self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0),
                                             at: .bottom,
                                             animated: animated)
        }, completion: nil)
    }
    

    If index is the index of the last item in the collection's view data source it'll scroll all the way to the bottom.

    0 讨论(0)
  • 2021-02-05 03:04

    Just to elaborate on my comment.

    viewDidLoad is called before elements are visual so certain UI elements cannot be manipulated very well. Things like moving buttons around work but dealing with subviews often does not (like scrolling a CollectionView).

    Most of these actions will work best when called in viewWillAppear or viewDidAppear. Here is an except from the Apple docs that points out an important thing to do when overriding either of these methods:

    You can override this method to perform additional tasks associated with presenting the view. If you override this method, you must call super at some point in your implementation.

    The super call is generally called before custom implementations. (so the first line of code inside of the overridden methods).

    0 讨论(0)
  • 2021-02-05 03:09

    So had a similar issue and here is another way to come at it without using scrollToItemAtIndexPath

    This will scroll to the bottom only if the content is larger than the view frame.

    It's probably better to use scrollToItemAtIndexPath but this is just another way to do it.

    CGFloat collectionViewContentHeight = myCollectionView.contentSize.height;
    CGFloat collectionViewFrameHeightAfterInserts = myCollectionView.frame.size.height - (myCollectionView.contentInset.top + myCollectionView.contentInset.bottom);
    
    if(collectionViewContentHeight > collectionViewFrameHeightAfterInserts) {
       [myCollectionView setContentOffset:CGPointMake(0, myCollectionView.contentSize.height - myCollectionView.frame.size.height) animated:NO];
    }
    
    0 讨论(0)
提交回复
热议问题