見出し画像

Swiftで行こう!--SwiftUIもっと!4

ループを使いたい場合です。ForEachを使います。

struct ContentView: View {
   var body: some View {
       VStack(alignment: .leading) {
           ForEach((1...10).reversed()) {
               Text("\($0)…")
           }
           
           Text("Ready or not, here I come!")
       }
   }
}
let content = ContentView()
PlaygroundPage.current.liveView = UIHostingController(rootView: content)

引数を簡略化しています。

Text("\($0)…")

こんな感じで出力されます。

配列の場合です。

 let colors: [Color] = [.red, .green, .blue]
   
   var body: some View {
       VStack {
           ForEach(colors.identified(by: \.self)) { color in
               Text(color.description.capitalized)
                   .padding()
                   .background(color)
                 
           }
       }
   }

colors.identified(by: \.self)で変数colorsの配列要素を取得します。

注意!:beta4になって少し変更担っています。上記コードは、

ForEach(colors.identified(by: \.self))は非推奨になり代わりに

ForEach(colors,id: \.self)

を使うようになります。

こんな感じです!

この記事が気に入ったらサポートをしてみませんか?