Search code examples
iosswiftuiscrollviewuicollectionview

How to scroll to the center of UICollectionView (Both Horizontally and Vertically)


I've implemented a collectionview that scrolls both horizontally and vertically (basically its a grid). I want to achieve being able to scroll to an item when it is selected with animation both vertically and horizontally.

Currently I'm using this as a "workaround" but it still jumps for obvious reasons.

 self.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
 self.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)

Is there anyway to achieve what I want to happen?


Solution

  • UICollectionView.ScrollPosition is an OptionSet.

    Did you try

    scrollToItem(at: indexPath, at: [.centeredVertically, .centeredHorizontally], animated: false)
    

    ?