UICollection View is a tool for displaying a collection of items in a grid-like or custom layout. So In this blog, We will learn how to Scroll UICollectionView automatically in Swift.
Setting Up the UICollectionView
Before Working on the automatic scrolling of UICollectionView, you should have some basic idea about the UICollectionView in Swift. Now Follow the below steps and set up the collection view for the automatic scrolling.
1. Create New Project:- First, create a fresh project or open an existing project where you have integrated the UICollection View.
2. Design Your UICollection View:- Set up your UICollectionView either programmatically or using Storyboard.
3. Load Data:- Once you complete the basic setup for the UICollection View, populate your UICollectionView with the data that you want to display on the screen. Ensure you’ve established the UICollectionViewDelegate and UICollectionViewDataSource for your Collection View.
Once you complete the UI Collection view setup your collection view should look like this:-
Implementing Automatic Scrolling
To implement auto-scrolling in your collection view, follow these steps.
Step 1:- Timer Setup
Timer setup will trigger the scrolling method automatically in provided intervals.
1 2 3 4 |
var timer: Timer? let timeInterval: Double // Add the double value here like 2.0 var currentIndex: = 0 // To keep track of the scrolling var itemList : [String] // List of Image |
Step 2:- Scroll Logic
Once you define all the variables that we are gonna need for scroll logic, create a function to handle the scrolling action.
1 2 3 4 5 6 7 8 9 |
@objc func scrollNext(){ if(currentIndex < itemList.count - 1){ currentIndex = currentIndex + 1; }else if (currentIndex == itemList.count - 1){ currentIndex = 0; } collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: .right, animated: true) } |
Step 3:- Start Auto-Scroll
Now we have added the scroll logic and we need to call this logic with the constant interval of time. Initialize the timer and add a selector and time interval for the scrolling.
1 |
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(scrollNext), userInfo: nil, repeats: true) |
Note:- You can initialize the timer anywhere according to your needs as we have initialized the timer under override func viewDidLoad().
Once you complete all three steps, your UICollectionView will start scrolling like below:-
Conclusion
So, In this article, we have learned about how to scroll UICollectionView automatically in Swift.
You can check out more amazing articles with the Mobikul Blogs.