首页 > 解决方案 > 使用计时器切换图像 (SwiftUI)

问题描述

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

截屏

标签: iosswiftswiftuiuipageviewcontroller

解决方案


用于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
    }

推荐阅读