Search code examples
iosswiftswiftuiuipageviewcontroller

Switch images using timer (SwiftUI)


I use the UIPageViewController to show images. I need a timer to show the images one after another, after every 5 seconds. How do I initiate an event to move to the next image after 5 seconds using the timer?

screenshot


Solution

  • Use Timer.publish to create a timer instance field like so:

    let images = [...] // Array of image names to show
    @State var activeImageIndex = 0 // Index of the currently displayed image
    
    let imageSwitchTimer = Timer.publish(every: 5, on: .main, in: .common)
                                .autoconnect()
    

    Then use the .onReceive() modifier of any view to go to the next image:

    Image(named: images[activeImageIndex])
        .onReceive(imageSwitchTimer) { _ in
            // Go to the next image. If this is the last image, go
            // back to the image #0
            self.activeImageIndex = (self.activeImageIndex + 1) % self.images.count
        }