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

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

【问题讨论】:

    标签: ios swift swiftui uipageviewcontroller


    【解决方案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 方法。 工作一种享受

      【讨论】:

        猜你喜欢
        • 2021-09-11
        • 2021-09-15
        • 1970-01-01
        • 2020-03-26
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-25
        相关资源
        最近更新 更多