SwiftUI navigation link screen pops when change color theme

I have a TabBar view with a single tab (for the demo purposes). The tab view screen has a NavigationLink button which sends you to a screen with a Text box only. The problem that occurs is that whenever I am on the second screen and change the color theme one time – nothing special happens, theme changes and all. When I change it a second time afterwards, the screen just dismisses itself without a reason. Anyone has any idea why this might be happenning?

struct MyTabView: View {
    @Environment(\.colorScheme) var colorScheme
    @State var toggle = false
    
    var body: some View {
        TabView {
            ContentView(toggle: $toggle)
                .tabItem {
                    Text("Profile")
                        .foregroundColor(colorScheme == .dark ? .white : .black)
                }
        }
        .accentColor(colorScheme == .dark ? .white : .black)
        .navigationBarTitleDisplayMode(.inline)
    }
}

struct ContentView: View {
    @Binding var toggle: Bool
    
    var body: some View {
        NavigationLink(destination: Text("madmasdmsadas"), isActive: $toggle) {
            Text("Click")
        }
    }
}

@main
struct AppTesting: App {
    var body: some Scene {
        WindowGroup {
            NavigationView {
                MyTabView()
            }
        }
    }
}

I tried adding binding values to keep it active but the problem doesn’t get resolved.

>Solution :

Ideally, the NavigationView should be under TabView. Not vice versa.

As for why this is happening: I don’t have a clear thought about this. Perhaps a bug that causes the toggle state to reset. But updating the code accordingly has helped me.

The updated code:

import SwiftUI

struct MyTabView: View {
  @Environment(\.colorScheme) var colorScheme
  @State var toggle = false
  
  var body: some View {
    TabView {
      NavigationView {
        ContentView(toggle: $toggle)
      }
      .tabItem {
        Text("Profile")
          .foregroundColor(colorScheme == .dark ? .white : .black)
      }
    }
    .accentColor(colorScheme == .dark ? .white : .black)
    .navigationBarTitleDisplayMode(.inline)
  }
}

struct ContentView: View {
  @Binding var toggle: Bool
  
  var body: some View {
    NavigationLink(destination: Text("madmasdmsadas"), isActive: $toggle) {
      Text("Click")
    }
  }
}

@main
struct AppTesting: App {
  var body: some Scene {
    WindowGroup {
      MyTabView()
    }
  }
}

Leave a Reply