3
0

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.

【WWDC23】SwiftUIのPreviewで@Stateを使用する方法

Last updated at Posted at 2023-06-06

はじめに

2023年6月6日、今年もWWDCが開催されました。
SwiftUIにもいくつか変更があり、その中でもまずPreviewの変更が目につきました。

Preview

以前までは、SwiftUIでBindingを使用した時のプレビューはこのように書いていました。

import SwiftUI

struct ContentView: View {
    @Binding var text: String
    
    var body: some View {
        VStack {
            TextField("", text: $text)
        }
        .padding()
    }
}

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

ところが、今回からPreviewの書き方が大きく変わり、このように書くことでPreviewにStateを持たせられるようになりました。

import SwiftUI

struct ContentView: View {
    @Binding var text: String
    
    var body: some View {
        VStack {
            TextField("", text: $text)
        }
        .padding()
    }
}

#Preview {
    @State var text = ""
    
    return ContentView(text: $text)
}

おわりに

だいぶ簡潔に書けるようになりました😆

Twitter

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?