UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 23 - Conditional Modifiers

Forums > 100 Days of SwiftUI

Hey,

What is the best way to return a different view, depending on the state of a boolean property? In the below example I'm trying to return var view1 in var body: some View if @State private var showTextView1 is true, and var view2 if @State private var showTextView1 is false. Because view1 and view2 are different types it won't let me use the code below, so I was wondering if anyone could point me in the right direction?

struct ContentView: View {
    @State private var showTextView1 = true

    var view1: some View {
        VStack {
            Button("Click on me") {
                self.showTextView1.toggle()
            }
            Text("Hello")
        }
    }

    var view2: some View {
        VStack {
            Button("Click on me") {
                self.showTextView1.toggle()
            }
            Text("Goodbye")
        }
    }

    var body: some View {
        showTextView1 ? view1 : view2
    }
}

Thanks!

3      

you can return an AnyView

 var body: some View {
        showTextView1 ? AnyView(view1) : AnyView(view2)
    }

4      

You can also do

var body: some View {
    if showTextView1 {
        view1
    } else {
        view2
    }
}

or you can do another computed property

var eitherView: some View {
    Group {
        if showTextView1 {
            view1
        } else {
            view2
        }
    }
}

and in body do

var body: some View {
    eitherView
}

4      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.