2
2

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 1 year has passed since last update.

SwiftUIAdvent Calendar 2023

Day 5

SwiftUI流 リアルタイム表示

Last updated at Posted at 2023-12-04

リアルタイムの日時を表示する記事をときどき見かけたので、SwiftUIしか知らない私なりのコードを残しておきます。

import SwiftUI

struct RealTimeView: View {
    @State private var date = Date.now

    private let timer = Timer.publish(
        every: 1.0,
        on: .main,
        in: .default)
        .autoconnect()

    private let format = Date.FormatStyle(
        date: .abbreviated,
        time: .standard)

    var body: some View {
        Text(date, format: format)
            .font(.title)
            .monospacedDigit()
            .onReceive(timer) { realDate in
                date = realDate
            }
    }
}

#Preview {
    RealTimeView()
}

プレビュー

2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?