LoginSignup
3
2

More than 1 year has passed since last update.

【SwiftUI】Previewで@Stateを使用したい

Posted at

はじめに

SwiftUIでBindingを使用するとPreviewの時にどうすればいいのか迷いますよね。
私が初学者の時はどうするのかわからずにPreviewを消してました。
同じような問題で困ってる人のために記事にします。

やりかた

ContentView
import SwiftUI

struct ContentView: View {
    @Binding var text: String
    var body: some View {
        Text(text)
    }
}

struct ContentView_Previews: PreviewProvider {
+   @State static var text: String = "テスト"
    static var previews: some View {
        ContentView(text: $text)
    }
}

ポイント
@Statestaticを付けます。

おわり

.constant()でもPreviewを表示させることができます。

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