Make automatic image slider in iOS
Introduction
Many mobile applications use the image slider to view images, we want to automate the slider to move images this looks very interesting for the user.
Overview
In this demo, we will learn how to make an automatic image slider using UICollectionView and UIPageControl.
Steps
First, create a single view application
Add a CollectionView to your view controller
Assign constraints to auto image slider CollectionView
Select UICollectionView Cell and add ImageView to the cell
Assign constraints to the ImageView inside the CollectionView Cell
Setup the CollectionView Delegate and Datasource, assign them to the ViewController.
Add PageControl to the View Controller
Assign constraints to the PageControl inside the ViewController.
Make the bottom of PageControl the same as the bottom of the CollectionView and make constant = -5
Make outlets for both the CollectionView and the PageControl
Add the Images to the Assets and initialize the array with the images, that will use in the automatic image slider CollectionView
Create a new class for the CollectionView Cell
Create an outlet for the ImageView in the CollectionView cell class
Give the CollectionView Cell identifier
Now let make the ViewController conform to both the UICollectionViewDelegate, UICollectionViewDataSource protocols
make the ViewController conform to UICollectionViewDelegateFlowLayout protocol
Note: If you are using swift 5 or xcode 11 and later you need to set Estimate Size
to none
using storyboard in order to make it work properly.
Make the CollectionView has a horizontal scroll direction and hides the indicator and allow paging
Setup the page control
Setup the indicators of the page control as the CollectionView scrolls, add this method to the ViewController
Now the CollectionView scrolls images with the user interaction and page control indicates the current page
Let’s Automate scrolling
First, we create a timer and counter
Initialize the timer with a repeated scheduled timer
Define the sliding function
We defined the counter so as the counter is less than the count of the images array, the CollectionView slides to the next image, and when the counter reaches the last image, it returns back to the first image, and then we assign the counter to 1, so the CollectionView doesn’t stand at the image of index zero 2 seconds.
Conclusion
This demo shows how to make an automatic image slider using CollectionView, Page Control, Repeated Timer, and Counter.
I hope this demo demonstrates the idea and helped you.
I would be grateful if you shared this article on Facebook, Twitter, and Linkedin.
Thanks.