GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Conditional Navigation Link with stepper output

Forums > SwiftUI

I want to link to a different view depending on what the output on the stepper is. This is what I tried:

struct ContentView: View {
    @State private var time = 5  

    var body: some View {
        NavigationView {
            HStack {
                Text("\(time) Minutes")
                Stepper("", value: $time, in: 2...15)
                Text("Go to session")
                NavigationLink(destination: {

                VStack {
                    Text("Start session")

                    if time == 2 {
                        Session2()
                    }
                     if time == 3 {
                        Session3()
                    }
                     if time == 4 {
                        Session4()
                    }
                     if time == 5 {
                        Session5()
                    }
                    //...

                }

                }())
            }
        }
    }
    }

I can't seem to get it to work. Is there any way this would be possible in SwiftUI?

3      

Paul discusses it here under Programmatic navigation.

SwiftUI’s NavigationLink has a second initializer that has an isActive parameter, allowing us to read or write whether the navigation link is currently active. In practical terms, this means we can programmatically trigger the activation of a navigation link by setting whatever state it’s watching to true.

https://www.hackingwithswift.com/articles/216/complete-guide-to-navigationview-in-swiftui

3      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.