How do I implement a custom layout stack to take children instead of a parameter in SwiftUI?

Viewed 116

I'm new to iOS development so I apologize in advance for any incorrect terminology.

I've implemented a custom layout using a combination of VStacks and HStacks and it works fine. However, I would like to make generic and reusable.

This is what I'm currently doing:

UniformGrid(rows: 5, columns: 5, content: [String])

The problem with that is that I have hardcoded what the child views are.

What I want is:

UniformGrid(rows: 5, columns: 5) {
     Text("Dogs")
     Image("cats")
     ...
}

Can anyone give me some direction on how to achieve this?

1 Answers

You can use this way:

struct UniformGrid <Content>: View where Content: View {

    let content: () -> Content
    var row: Int
    var column: Int

    init(row: Int, column: Int, @ViewBuilder content: @escaping () -> Content) {
        self.content = content
        self.row = row
        self.column = column
    }

    var body: some View {
        content()
    }
}

In your root view:

struct ContentView: View {

    var body: some View {
        UniformGrid(row: 5, column: 5) {
            Text("")
        }
    }
}
Related