I have a collection view in my view. In the cells are image views and it has one section.
I now want to scroll programmatically through the images. I want the animation to happen endless so it starts with item one after reaching item 10.
It also would be helpful if you provide some method where to put animations like the cells getting bigger after getting programmatically swiped in from right.
There are two methods that could help you achieve this:
func scrollToItemAtIndexPath(indexPath: NSIndexPath, atScrollPosition scrollPosition: UICollectionViewScrollPosition, animated animated: Bool)
or
func setContentOffset(contentOffset: CGPoint, animated animated: Bool)
Both are on UICollectionView
so you can use whatever seems more convenient. To create a custom animation for this however is more difficult. A quick solution depending on what you need could be this answer.
Swift 4, iOS 11:
// UICollectionView method func scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) // UIScrollView method func setContentOffset(_ contentOffset: CGPoint, animated: Bool)
Swift 5
Based on Mr.Bean's answer, here is an elegant way using UICollectionView extension:
extension UICollectionView { func scrollToNextItem() { let contentOffset = CGFloat(floor(self.contentOffset.x + self.bounds.size.width)) self.moveToFrame(contentOffset: contentOffset) } func scrollToPreviousItem() { let contentOffset = CGFloat(floor(self.contentOffset.x - self.bounds.size.width)) self.moveToFrame(contentOffset: contentOffset) } func moveToFrame(contentOffset : CGFloat) { self.setContentOffset(CGPoint(x: contentOffset, y: self.contentOffset.y), animated: true) } }
Now you can use it wherever you want:
collectionView.scrollToNextItem() collectionView.scrollToPreviousItem()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With