G. Marc
G. Marc

Reputation: 6037

How to create view with multiple subviews like VStack in SwiftUI

I've created a custom view which is basically a VStack with modifiers applied to it. But unlike the original VStack view, I have to use a grouping view when I'm using it with multiple subviews.

How can I get rid of the "Group" in the below example?

import SwiftUI

struct ContentView: View {
    var body: some View {
        CustomGroup() {
            Group {
                Text("Hello")
                Text("World")
            }
        }
    }
}

struct CustomGroup<Content>: View where Content : View {
    let content: () -> Content
    
    var body: some View {
        VStack() {
            content()
        }
        .background(Color.yellow)
        .cornerRadius(8)
    }
}

Upvotes: 1

Views: 1296

Answers (1)

Asperi
Asperi

Reputation: 258117

You need init with ViewBuilder

Here is a solution. Tested with Xcode 12 / iOS 14

struct TestCustomGroup: View {
    var body: some View {
        CustomGroup {
            Text("Hello")
            Text("World")
        }
    }
}

struct CustomGroup<Content>: View where Content : View {
    let content: () -> Content

    init(@ViewBuilder _ content: @escaping () -> Content) {
        self.content = content
    }

    var body: some View {
        VStack {
            content()
        }
        .background(Color.yellow)
        .cornerRadius(8)
    }
}

Upvotes: 2

Related Questions