Skip to content

GeorgeElsham/ViewExtractor

Repository files navigation

ViewExtractor

Extract SwiftUI views from ViewBuilder content.

Installation

Follow the instructions at Adding Package Dependencies to Your App to find out how to install the Swift package. Use the link of this GitHub repo as the URL (https://github.com/GeorgeElsham/ViewExtractor).

Example

Here is an example which creates a VStack with Divider()s in between.

View code

struct DividedVStack: 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(spacing: 0) {
            ForEach(views.indices) { index in
                if index != 0 {
                    Divider()
                }
                
                views[index]
            }
        }
    }
}

Usage

DividedVStack {
    Text("View 1")
    Text("View 2")
    Text("View 3")
    Image(systemName: "circle")
}

Result

About

Extract SwiftUI views from ViewBuilder content.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages