1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift UI】ObservableObjectとObservedObjectを理解するための時計アプリ

Posted at

この記事は何か

SwiftUIフレームワークによるアプリ開発におけるデータフローを理解するために、シンプルな時計アプリを作成します。

環境

macOS 11.1
Xcode 12.3
Swift 5.3

コード

アプリのエントリーポイント
@main
struct WatchApp: App {
    let clock = Clock()
    
    var body: some Scene {
        WindowGroup {
            ContentView(clock: clock)
        }
    }
}
ObservableObjectのクラス
class Clock: ObservableObject {
    var timer = Timer()
    @Published var currentTime = ""
    
    init() {
        start()
    }
    
    func start() {
        let formatter = DateFormatter()
        formatter.timeStyle = .medium
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (_) in
            self.currentTime = formatter.string(from: Date())
        })
    }
    
    func stop() {
        timer.invalidate()
    }
}
ContentView
import SwiftUI

struct ContentView: View {
    @ObservedObject var clock = Clock()
    
    var body: some View {
        Text("\(clock.currentTime)")
            .font(.title)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView(clock: Clock())
        }
    }
}

スクリーンショット 2021-01-24 3.21.09.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?