swiftxcodeanimationicarousel

Repeating iCarousel's scrolling


I'm using iCarousel in Swift 3 in Xcode. I'm trying to make it work like a sliding banner. I have this function:

func animate() {
    DispatchQueue.global(qos: .userInteractive).async {
        self.carousel.scrollToItem(at: 0, animated: false)

        while(true){
            sleep(3)
            self.carousel.scroll(byNumberOfItems: 1, duration: 0.3)
        }
    }
}

I call it in viewDidLoad. It works but I think it's not as good as it could be. After I switch to another view, scrolling goes on and on. What would be the best approach to make it scroll only, when I'm seeing the view, that the carousel is in?


Solution

  • What solved the problem:

    var timer: Timer!
    
    self.timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.handleTimer), userInfo: nil, repeats: true)
    
    func handleTimer(){
            self.carousel.scroll(byNumberOfItems: 1, duration: 0.3)
        }