[英]Switch images using timer (SwiftUI)
使用Timer.publish
创建一个计时器实例字段,如下所示:
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()
然后使用任何视图的.onReceive()
修饰符转到下一张图像:
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
}
你也可以使用 @State private var[..].shuffled() 方法来拥有你的数组
然后装入您的计时器
计时器的 onReceive 方法。 工作款待
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.