はじめに
iOS15からTimelineView
というものが登場していたらしいです
コンポーネント一覧を見ていたら発見しました笑
気になったのでTimelineView
を使用して簡単なアプリを作成しようと思います。
完成形
完成コード
import SwiftUI
struct ContentView: View {
var body: some View {
GeometryReader { geo in
ZStack(alignment: .center) {
Color(red: 132/255, green: 209/255, blue: 78/255).edgesIgnoringSafeArea(.all)
TimelineView(.periodic(from: Date(), by: 1)) { timeline in
VStack(alignment: .center, spacing: 10) {
Text("\(timeline.date.formatted(.iso8601.year().month().day().dateSeparator(.dash)))")
.fontWeight(.medium)
.font(.custom("DSEG7Modern-BoldItalic", size: geo.size.width/15))
.foregroundColor(.black)
.background(
Text("8888-88-88")
.fontWeight(.medium)
.font(.custom("DSEG7Modern-BoldItalic", size: geo.size.width/15))
.foregroundColor(.black.opacity(0.1))
)
Text("\(timeline.date.formatted(.iso8601.time(includingFractionalSeconds: false)))")
.fontWeight(.medium)
.font(.custom("DSEG7Modern-BoldItalic", size: geo.size.width/6))
.foregroundColor(.black)
.background(
Text("88:88:88")
.fontWeight(.medium)
.font(.custom("DSEG7Modern-BoldItalic", size: geo.size.width/6))
.foregroundColor(.black.opacity(0.1))
)
}
}
}
}
}
}
解説
時間の更新
今回のメインであるTimelineView
は以下のような使い方になります。
TimelineView(.periodic(from: Date(), by: 1)) { timeline in
}
timeline
からdate
を取り出します
// 日付
Text("\(timeline.date.formatted(.iso8601.year().month().day().dateSeparator(.dash)))")
// 時間
Text("\(timeline.date.formatted(.iso8601.time(includingFractionalSeconds: false)))")
日本時間にしたい場合、timeZoneを設定してください
フォント
カスタムフォントを設定しています。
フォントサイズは適当なので各自調整してください。
一応、iPad 11inch, iPhoneSE, iPhone12で正常に表示される事を確認しました
.font(.custom("DSEG7Modern-BoldItalic", size: geo.size.width/15))
文字背景に焼き付きを表示
88を重ねることによってデジタル時計感が増します
.background(
Text("8888-88-88")
.fontWeight(.medium)
.font(.custom("DSEG7Modern-BoldItalic", size: geo.size.width/15))
.foregroundColor(.black.opacity(0.1))
)
おわり
iOS15以前だと定期的に更新するにはtimer
やonReceive
を使用するなど面倒でした。
しかし、TimelineView
の登場により、定期更新が簡単になった気がします。
完成プロジェクトを置いときます。