繁体   English   中英

使用计时器 (SwiftUI) 切换图像

[英]Switch images using timer (SwiftUI)

我使用UIPageViewController来显示图像。 我需要一个计时器来一个接一个地显示图像,每 5 秒一次。 如何使用计时器在 5 秒后启动一个事件以移动到下一个图像?

截屏

使用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.

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