Enrico
Enrico

Reputation: 178

How to return a view with ViewModifiers

I want to return a View depending on content of an field in a array. This works, but i got a problem if i try to add ViewModifiers to the View. This won't works.

struct CodesView: View {
    var body: some View {
            ScrollView{
                ForEach(0 ..< codes.count) {idx in
                    Result(selector: self.codes[idx].Zeile)
                }
            }
       }
   }
    struct Result: View{
        var selector: String

        var body: some View{
            switch selector {
            case "->Text1":
                return VStack{
                    Text("Lorem ipsum dolor sit amet")
                    .bold()
                }
            // serval other case will follow...
            default:
                return VStack{
                    Text("\(selector)")
                    .frame(width: 350, alignment: .leading)    // line throw an error
                    .font(.system(.body, design: .monospaced)) // line throw an error 
                }
            }
        }
    }

Errormessage is: Function declares an opaque return type, but the return statements in its body do not have matching underlying types

How do I need to declare the function to get the result with ViewModifier? I need different layout for the different returned Views.

Upvotes: 1

Views: 637

Answers (2)

Chris
Chris

Reputation: 8091

you cannot use switch statements in body. Just simple "if" are allowed here.

but check this answer here, it helps: Alternative to switch statement in SwiftUI ViewBuilder block?

Example:

enum T {
    case a
    case b
}

struct ContentView: View {

    var a : T =  .a

    var body : some View {

        Group { () -> Text in
            switch a {
            case .a:
                return Text("a")
            case .b:
                return Text("b")
            }
        }
    }
}

Upvotes: 0

Asperi
Asperi

Reputation: 257789

The following solves your case

struct Result: View {
    var selector: String

    var body: some View {
        Group {
            if self.selector == "->Text1" {
                VStack {
                    Text("Lorem ipsum dolor sit amet")
                        .bold()
                }
            } else {
                VStack {
                    Text("\(selector)")
                        .frame(width: 350, alignment: .leading)
                        .font(.system(.body, design: .monospaced))
                }
            }
        }
    }
}

Upvotes: 2

Related Questions