I've ImageView placed inside UICollectionViewCell and a PageControl below it. Both are connected via programmatically.
However, I want auto swipe (say every 5 seconds) the images should auto swipe.
If user swipe manually then too it should happen. Also, when page control reaches to last it should begin with first.
Below is code that I've used :
var offersImages: [UIImage] = [ //Array of Banners
UIImage(named: "default-banner.png")!,
UIImage(named: "default-banner.png")!,
UIImage(named: "default-banner.png")!,
UIImage(named: "default-banner.png")!,
]
override func viewDidLoad() {
super.viewDidLoad()
self.objPageControl.currentPage = 0
self.objPageControl.numberOfPages = self.offersImages.count
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let pageWidth : CGFloat = self.objBannerCollectionView.frame.size.width
self.objPageControl.currentPage = Int(self.objBannerCollectionView.contentOffset.x/pageWidth)
}
How can this be done in Swift?
Below code solved my problem :
//MARK:- viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
. . .
_ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(moveToNextPage), userInfo: nil, repeats: true)
}
func moveToNextPage (){
let pageWidth:CGFloat = self.objBannerCollectionView.frame.width
let maxWidth:CGFloat = pageWidth * 4
let contentOffset:CGFloat = self.objBannerCollectionView.contentOffset.x
var slideToX = contentOffset + pageWidth
if contentOffset + pageWidth == maxWidth {
slideToX = 0
}
self.objBannerCollectionView.scrollRectToVisible(CGRect(x:slideToX, y:0, width:pageWidth, height:self.objBannerCollectionView.frame.height), animated: true)
}