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

SOLVED: How to conditionally navigate to a different view within a List or ForEach?

Forums > SwiftUI

Hey everyone,

I have two different views that I want to display to the user depending on if a variable within a data array is marked as a "pod". I'm having trouble implementing the conditional within the List/ForEach, as no matter how I implement, the destination stays the same. Here's an example of the list:

List {
                    ForEach(getrealmdata.plantarray) { plants in
                        NavigationLink(destination: FloraPodDetailView(plantdata: plants, plantsensor: self.plantsensor)) {
                        PlantSensorRealmRow(plantsensor: self.plantsensor, plantdata: plants)
                        }
                    }.onDelete(perform: delete)
                }

The plantdata object contains a variable named sensortype that I want to read - this type is either "pod" or "plant".

Basically, I want the destination to go to PlantDetailViewNew if the plantdata.sensortype = plant, and it should go to FloraPodDetailView if plantdata.sensortype = pod.

Any ideas how I should construct this?

3      

One way:

var body: some View {
    NavigationView {
        VStack(spacing: 20) {
            NavigationLink("Push (One)", destination: PushedView(text: "one"),
                           tag: 1,
                           selection: self.$selected)

            NavigationLink("Push (Two)", destination: PushedView(text: "two"),
                           tag: 2,
                           selection: self.$selected)

            NavigationLink("Push (Three)", destination: PushedView(text: "three"),
                           tag: 3,
                           selection: self.$selected)

            DelayButton(selected: self.$selected, tagId: 1)
            DelayButton(selected: self.$selected, tagId: 2)
            DelayButton(selected: self.$selected, tagId: 3)
        }
    }
}

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.