1 year ago

#363069

test-img

hopy

SwiftUI incorrect navigation behavior in iOS 14.2

The view navigation hierarchy of my code is as follows:

  • ColorsView
    • WarmColorsView
      • RedView
    • CoolColorsView

Which is ColorsView can navigate directly to WarmColorsView and CoolColorView, and WarmColorsView can navigate directly to RedView.

Here is code (very simple):

import SwiftUI

class Model: ObservableObject {
    @Published var tagNavToWarmOrCool: String?
    @Published var isNavToRed = false
}

struct RedView: View {
    
    @EnvironmentObject var model: Model
    
    var body: some View {
        VStack {
            Button("to cool colors"){
                model.isNavToRed = false
                model.tagNavToWarmOrCool = "cool"
            }
        }
    }
}

struct CoolColorsView: View {
    var body: some View {
        VStack {
            
        }
        .navigationTitle("Cool Colors")
    }
}

struct WarmColorsView: View {
    
    @EnvironmentObject var model: Model
    
    var body: some View {
        NavigationLink("red", destination: RedView(), isActive: $model.isNavToRed)
            .navigationTitle("Warm Colors")
    }
}

struct ColorsView: View {
    @EnvironmentObject var model: Model
    
    var body: some View {
        VStack {
            NavigationLink("to warm colors", destination: WarmColorsView(), tag: "warm", selection: $model.tagNavToWarmOrCool)
            
            NavigationLink("to cool colors", destination: CoolColorsView(), tag: "cool", selection: $model.tagNavToWarmOrCool)
        }
        .navigationTitle("Colors")
    }
}

struct ContentView: View {
    
    @StateObject var model = Model()
    
    var body: some View {
        NavigationView {
            ColorsView()
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .environmentObject(model)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(Model())
    }
}

My intention is to go to the RedView, and then click the button to navigate to the CoolColorsView.

Running in iOS 14.2, however it ends up navigating to the ColorsView, I tried to change NavigationView's style to default, but it didn't work.

There is no such problem in iOS 15.4.1!

So how to navigate from RedView to CoolColorsView by click button in RedView in iOS 14.2? Thanks a lot! :)

swiftui

navigation

ios14

swiftui-navigationlink

0 Answers

Your Answer

Accepted video resources