使用计时器切换图像(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 方法。 大快朵颐