Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewScrollPosition not working

i have a collectionview that i am trying to scroll programatically. the problem being that if the cell i want to scroll to is visible in the collection view it doesn't scroll it to the centre. so for the image below the lower cell is item 1. and it does not scroll to it but it will scroll past item 1 to item 2.

i have been trying to use UICollectionVieScrollPosition.CenterVertically but this does not seem to work.

self.collectionView?.scrollToItem(at: IndexPath(row: 1, section: 0), at: UICollectionViewScrollPosition.centeredVertically, animated: true)

is there a way around this to force the scrolling of cells that are visible to the centre of the collection?

enter image description here

like image 277
Pippo Avatar asked Nov 28 '22 16:11

Pippo


2 Answers

the best way i found to do this is to not use scrollToItem but to get the CGRect of the index and then make that visible.

     let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(row: 5, section: 0))?.frame
     self.collectionView.scrollRectToVisible(rect!, animated: false)
like image 73
Pippo Avatar answered Dec 05 '22 15:12

Pippo


I'm trying to delay it with 0.1s. For my case, looks good for now:

collectionView.collectionViewLayout.invalidateLayout() //just in case, iOS10 may crash btw.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}

Update:

ok, turns out that I'm using layout.estimatedItemSize and autolayout to calculate the width of my cells, that's why I have this problem. That says, for me, it's because of CollectionView's dynamic sizing. After I back to calculate the width manually, everything works fine. (by using -collectionView:layout:sizeForItemAt:)

like image 32
boog Avatar answered Dec 05 '22 13:12

boog