简体   繁体   中英

Swiftui foreach inside parameter

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

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() }

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM