简体   繁体   中英

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?

截屏

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
    }

You could also have your array using a method @State private var[..].shuffled()

Then encase in your Timer

onReceive method for your timer. Works a treat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM