はじめに
謎のバグに遭遇する時は意図しないタイミングでViewに更新がかかってるからかもしれません。
Viewの更新を知る方法を2つ知ったので記事にしておきます。
方法1
import SwiftUI
struct ContentView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 50) {
let _ = print("Viewを更新しました")
Text(count.description)
Button {
count += 1
} label: {
Text("カウントアップ")
}
}
}
}
Viewを更新しました
Viewを更新しました
Viewを更新しました
Viewを更新しました
方法2
import SwiftUI
struct ContentView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 50) {
let _ = Self._printChanges()
Text(count.description)
Button {
count += 1
} label: {
Text("カウントアップ")
}
}
}
}
ContentView: @self, @identity, _count changed.
ContentView: _count changed.
ContentView: _count changed.
ContentView: _count changed.
おわり
_printChanges()
のほうは詳細な情報を出力できますが、
プライベートAPIなのでAppleに提出する際は消しておいた方が良いでしょう