helpMeCodeSwift
helpMeCodeSwift

Reputation: 93

SwiftUI Control flow build elements

I recently started playing with SwiftUI and though there are some good things too it, so far I am very disappointed. Especially by the fact that it makes it really easy to create large, messy looking code and reminds me of XML ( or HTML ) structure of sorts. Anyhow, I am running into the following problem that I can't find a solution for anywhere. I need to draw certain rectangles ( or shapes ) at run time, think about it as generating a horizontal bar-chart in a way. Because the number of rects is dynamic, I need to generate this in a method, however I am getting an error from the compiler with any method I've tried so far.

Whenever I try and use some sort of flow control, like 'for' or 'while' in order to generate elements inside the:

struct ContentView: View {

or :

 var body: some View {

I either get:

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

or

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

What would be a better approach for drawing dynamic elements with SwiftUI. I've seen a ton of examples on dynamic lists, even though that was covered by Apple already on day 1, but nothing that would be about custom elements or if you wanted to create a dynamically set number of HStack or Vstack, that are not formatted as a List.

Thank you!

Upvotes: 0

Views: 704

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163288

ViewBuilders are special things and you cannot use certain control flow statements in them.

You can call out to separate (private) functions to do the appropriate control flow and produce the appropriate views.

See this blog post by John Sundell on the Swift 5.1 features that power SwiftUI: https://www.swiftbysundell.com/articles/the-swift-51-features-that-power-swiftuis-api/

Upvotes: 1

Related Questions