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.