1

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

1 Answer 1

2

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.