How to make UICollectionView auto scroll using NSTimer?
Swift 4.2
With Runloop and Timer block. Adjust the 0.015 & 0.25 values to match your required speed.
var carousalTimer: Timer?
var newOffsetX: CGFloat = 0.0
func startTimer() {
carousalTimer = Timer(fire: Date(), interval: 0.015, repeats: true) { (timer) in
let initailPoint = CGPoint(x: self.newOffsetX,y :0)
if __CGPointEqualToPoint(initailPoint, self.collectionView.contentOffset) {
if self.newOffsetX < self.collectionView.contentSize.width {
self.newOffsetX += 0.25
}
if self.newOffsetX > self.collectionView.contentSize.width - self.collectionView.frame.size.width {
self.newOffsetX = 0
}
self.collectionView.contentOffset = CGPoint(x: self.newOffsetX,y :0)
} else {
self.newOffsetX = self.collectionView.contentOffset.x
}
}
RunLoop.current.add(carousalTimer!, forMode: .common)
}
// Swift-3
var timr=Timer()
var w:CGFloat=0.0
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
configAutoscrollTimer()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(true)
deconfigAutoscrollTimer()
}
func configAutoscrollTimer()
{
timr=Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(dashboard_ViewController.autoScrollView), userInfo: nil, repeats: true)
}
func deconfigAutoscrollTimer()
{
timr.invalidate()
}
func onTimer()
{
autoScrollView()
}
func autoScrollView()
{
let initailPoint = CGPoint(x: w,y :0)
if __CGPointEqualToPoint(initailPoint, ticker.contentOffset)
{
if w<collection_view.contentSize.width
{
w += 0.5
}
else
{
w = -self.view.frame.size.width
}
let offsetPoint = CGPoint(x: w,y :0)
collection_view.contentOffset=offsetPoint
}
else
{
w=collection_view.contentOffset.x
}
}
// this works excellently