Home > Enterprise >  Swiftui foreach inside parameter
Swiftui foreach inside parameter

Time:11-02

how to foreach inside the view parameter

this is my code

  CarouselView(itemHeight: 124, views: [
                                SliderItemView(),
                                SliderItemView(),
                                SliderItemView(),
                ])

i want to iterate and show the SliderItemView with looping

CodePudding user response:

ForEach cannot create an array. If you want to create an array of those views one way to do it would be [0..<3].map { _ in SliderItemView() }

CodePudding user response:

Here 2 way for solving your issue:

struct ContentView: View {
    
    var body: some View {

        CustomViewV1(content: {

            ForEach(0...2, id:\.self) { _ in Text("Hello, World!").foregroundColor(Color.blue) }

        })

        CustomViewV2(repeating: 3, content: { Text("Hello, World!").foregroundColor(Color.red) })
        
    }
    
}



struct CustomViewV1<Content: View>: View {
    
   @ViewBuilder let content: () -> Content
    
    var body: some View {
        
        return content()
        
    }
    
}

struct CustomViewV2<Content: View>: View {
    
    let repeating: Int
    @ViewBuilder let content: () -> Content
    
    var body: some View {

        if (repeating >= 1) {
            
            ForEach(1...repeating, id:\.self) { _ in
                
                content()
                
            }
            
        }
        
    }
    
}

result:

enter image description here

  • Related