使用 Swift 组合创建计时器发布器

2024-02-14

我一直在看通过 SwiftUI 的数据流 WWDC 演讲 https://developer.apple.com/videos/play/wwdc2019/226/。他们有一张包含示例代码的幻灯片,其中使用连接到 SwiftUI 视图的计时器发布器,并根据时间更新 UI。

我正在编写一些代码,我想做完全相同的事情,但无法弄清楚这是如何实现的PodcastPlayer.currentTimePublisher被实现,然后挂钩到 UI 结构。我还观看了所有关于Combine 的视频。

我怎样才能实现这个目标?

示例代码:

struct PlayerView : View {
  let episode: Episode
  @State private var isPlaying: Bool = true
  @State private var currentTime: TimeInterval = 0.0

  var body: some View {
    VStack { // ...
      Text("\(playhead, formatter: currentTimeFormatter)")
    }
    .onReceive(PodcastPlayer.currentTimePublisher) { newCurrentTime in
      self.currentTime = newCurrentTime
    }
  }
}

这里有一个组合计时器的示例。我使用的是全局的,但当然您应该使用适用于您的场景的任何内容(environmentObject、State 等)。

import SwiftUI
import Combine

class MyTimer {
    let currentTimePublisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .default)
    let cancellable: AnyCancellable?

    init() {
        self.cancellable = currentTimePublisher.connect() as? AnyCancellable
    }

    deinit {
        self.cancellable?.cancel()
    }
}

let timer = MyTimer()

struct Clock : View {
  @State private var currentTime: Date = Date()

  var body: some View {
    VStack {
      Text("\(currentTime)")
    }
    .onReceive(timer.currentTimePublisher) { newCurrentTime in
      self.currentTime = newCurrentTime
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Swift 组合创建计时器发布器 的相关文章

随机推荐