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

Posted

技术标签:

【中文标题】使用计时器切换图像 (SwiftUI)【英文标题】:Switch images using timer (SwiftUI) 【发布时间】:2019-12-15 04:51:43 【问题描述】:

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

【问题讨论】:

【参考方案1】:

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

【讨论】:

【参考方案2】:

您也可以使用 @State private var[..].shuffled() 方法获得您的数组

然后装进你的定时器

你的计时器的 onReceive 方法。 工作一种享受

【讨论】:

以上是关于使用计时器切换图像 (SwiftUI)的主要内容,如果未能解决你的问题,请参考以下文章