Tana Gone
Tana Gone
~1 min read

Categories

Observable Object protocolからObservable Macroへの移行ガイドを参考にmacOS App Projectを作ってみた。PreviewでData Bindingが機能している。 Apple DocumentationではObservable MacroとはデザインパターンのSwift版実装だと紹介されている。SwiftUIに組み込まれたCombineとは違い、Windows, Linuxでも動作するのだろう。
Migrating from the Observable Object protocol to the Observable macro | Apple Developer Documentation

import SwiftUI
//[SwiftUIでのタップ処理の実装と応用 #Swift - Qiita](https:qiita.com/yuu__uuki/items/833dbe566ebc855c2aed)
@Observable // プロパティの変化がインスタンスへ伝わる
class A {
  var i: Int = 0; var isOn: Bool = true
  var timer: Timer?
  init() { start() }
  func start() {
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
      self.i = Int.random(in: 100..<1000)
    }
  }
  deinit { timer?.invalidate() }
}

struct ContentView: View {
  var a: A
  var body: some View {
    // create Event Emitter
    VStack {
      Image(systemName: "globe")
        .resizable()
        .frame(width: 100, height: 100)
        .foregroundStyle(.tint)
      Text("Random: \(a.i)")
        .font(.system(size: 24, design: .monospaced))
    }
    .padding()
    .onTapGesture { // subscribe Event Emitter tab.
      if a.isOn { a.timer?.invalidate()
      } else { a.start() }
      a.isOn = !a.isOn
      print("Tapped!: \(a.i)") // Where is the event emmiter?
    }
  }
}

#Preview {
  ContentView(a: A())
    .frame(width: 200, height: 200)
}