3
3

More than 1 year has passed since last update.

【SwiftUI】Viewの更新をプリントする

Posted at

はじめに

謎のバグに遭遇する時は意図しないタイミングで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に提出する際は消しておいた方が良いでしょう

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