Home > Enterprise >  How can I feed ForEach with items of TupleView in SwiftUI?
How can I feed ForEach with items of TupleView in SwiftUI?

Time:11-26

I am trying to build a custom view which adds space between each content of TupleView, here is my pseudocode until now! What I should do more in codes to make it happen?

struct CustomSpacerView<Content1: View, Content2: View, Content3: View>: View {
    
    @ViewBuilder let content: () -> TupleView<(Content1, Content2, Content3)>
    
    var body: some View {

        ForEach(Array(arrayLiteral: content().value).indices, id:\.self) { index in
            
            Spacer()
            
            content().value.index
            
        }
        
        Spacer()
 
    }
    
}

use case:

struct ContentView: View {
    var body: some View {

        CustomSpacerView {

            Text("Hello, World!")
            
            Text("Hello, World!")
            
            Text("Hello, World!")
            
        }

    }
}

CodePudding user response:

You can use my ViewExtractor package. Here is an example with your code:

struct CustomSpacerView: View {
    private let views: [AnyView]

    // For 2 or more views
    init<Views>(@ViewBuilder content: TupleContent<Views>) {
        views = ViewExtractor.getViews(from: content)
    }

    // For 0 or 1 view
    init<Content: View>(@ViewBuilder content: NormalContent<Content>) {
        views = ViewExtractor.getViews(from: content)
    }

    var body: some View {
        VStack {
            ForEach(views.indices) { index in
                Spacer()

                views[index]
            }

            Spacer()
        }
    }
}

This has the same usage in ContentView.

As an overview, this works by getting a Mirror of the content, converting the raw bytes to a 'fake' type representing a View, then convert this Any type to AnyView.

  • Related