Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically scroll through a collection view?

Tags:

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.

like image 209
Lenny1357 Avatar asked Apr 16 '16 15:04

Lenny1357


2 Answers

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) 
like image 174
Jelly Avatar answered Oct 11 '22 06:10

Jelly


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() 
like image 29
Đorđe Nilović Avatar answered Oct 11 '22 08:10

Đorđe Nilović