Extract SwiftUI views from ViewBuilder content.
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
).
Here is an example which creates a VStack
with Divider()
s in between.
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]
}
}
}
}
DividedVStack {
Text("View 1")
Text("View 2")
Text("View 3")
Image(systemName: "circle")
}