drekka
drekka

Reputation: 21903

SwiftUI: How to call a function to populate a LazyVGrid

I'm working on some code in SwiftUI (learning as I go) where I'm constructing a vertical grid of items (This is heavily simplified for the purposes of this question):

let col1 = GridItem(alignment: .leading)
let col2 = GridItem(alignment: .trailing)

LazyVGrid(columns: [col1, col2]) {
    Text("C1")
    Text("C1")
    Text("C2")
    Text("C2")
}

So I get something like this:

+----+----+
| C1 | C1 |
+----+----+
| C2 | C2 |
+----+----+

Now in my code I'm doing some other stuff so I'd like to extract a function so my code looks something like this:

let col1 = GridItem(alignment: .leading)
let col2 = GridItem(alignment: .trailing)

LazyVGrid(columns: [col1, col2]) {
    row("C1")
    row("C2")
}

func row(text: String) -> ???? {
    Text(text)
    Text(text)
}

But I'm finding it difficult to see how to do it. Does the function return an array? or is there some aspect of Swift's builders I can use here? I tried an array but LazyVGrid's build didn't like it.

Upvotes: 1

Views: 195

Answers (1)

Steve M
Steve M

Reputation: 9794

Research the @ViewBuilder attribute. This makes the function behave like the closure you're passing to LazyVGrid and many of the SwiftUI Views.

@ViewBuilder
func row(text: String) -> some View {
    Text(text)
    Text(text)
}

Upvotes: 3

Related Questions