Creating Views with ForEach

Published by @SoNiceInfo at 6/24/2020


Use ForEach to create multiple identical views in a loop.
This section describes ForEach using an array of ranges, arrays, and struct.
After understanding ForEach in this page, let's see Create Instagram Home Screen or Using Mock Data for more challenging.

Range

The numbers from 1 to 10 are displayed in order.
By setting id: \.self, SwiftUI understand it's unique so that easily add or remove elements.
You can use that argument in a closure by passing it as an argument, such as num.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        VStack(alignment: .leading) {
            ForEach((1...10), id: \.self) { num in
                Text("\(num)")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
ForEach Basics

Array

Loop through the Color array with ForEach to make a button in the upper left corner of the window.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView: View {
    let colors: [Color] = [.red, .yellow, .green]

    var body: some View {
        HStack {
            ForEach(colors, id: \.self) { color in
                Text("●")
                    .font(.largeTitle)
                    .foregroundColor(color)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
The ForEach array

Array of structures

Create an array of structures (CatModel) and process it with ForEach.

//
//  ContentView.swift
//

import SwiftUI

struct CatModel {
    let id = UUID()
    let name: String
}

struct ContentView: View {
    let cats: [CatModel] = [CatModel(name: "Mike"), CatModel(name: "Tama"), CatModel(name: "Kuro")]

    var body: some View {
        VStack {
            ForEach(cats, id: \.id) { cat in
                Text(cat.name)
                    .font(.largeTitle)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Also, adding Identifiable protocol to the struct, you don't need id: \.id in ForEach
. The following code results in the same execution

//
//  ContentView.swift
//

import SwiftUI

struct CatModel : Identifiable {
    let id = UUID()
    let name: String
}

struct ContentView: View {
    let cats: [CatModel] = [CatModel(name: "Mike"), CatModel(name: "Tama"), CatModel(name: "Kuro")]

    var body: some View {
        VStack {
            ForEach(cats) { cat in
                Text(cat.name)
                    .font(.largeTitle)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
ForEach struct

References

ForEach - SwiftUI | Apple Developer Documentation


    I released iOS App!

    ToDo App

    Visualize Activity, Data sharing with iCloud, Dark mode supported.

    リリースしたToDoアプリのスクリーンショット

    IP Address bookmark.

    Check and bookamrk IP address of all interfaces with geolocation.

    リリースしたIPアドレス保存アプリのスクリーンショット