Home > AI > IOS > SwiftUI >

The relationship between List and ForEach

Example :


import SwiftUI




struct ContentView: View {

    struct dataModel: Hashable {
        var id: Int
    }
    var data = [
        dataModel(id: 1),
        dataModel(id: 2),
        dataModel(id: 3)
    ]
    
    
    var body: some View {
        // Example 1, just List
        
        List(data, id:\.self) { item in
            Text(String(item.id))
                .listRowBackground(Color.orange)
        }
        
        List {
            Image("avatar")
            Text("Title")
            Button(action: {
                print("Button tapped!")
            }) {
                Text("Energize!")
            }
        }
        
        
        List {
            Text("Food")
            ForEach(0..<2) { meal in
                Text("meals")
            }
            Text("Drinks")
            ForEach(0..<2) { drink in
                Text("drinks")
            }
        }
        
//        ForEach(data, id:\.self) { item in
//            Text(String(item.id))
//        }
        
        List {
            ForEach(data, id:\.self) { item in
                Text(String(item.id))
                    .listRowBackground(Color.blue)
            }
        }
    }
}



Leave a Reply