skip to Main Content

There is a bug in SwiftUI where NavigationLink behaves unexpectedly inside a TabView.
The NavigationLink inside a TabView is not preserved the View when returning from the main screen. The bug can be reproduced in iOS 16.1 on the iPhone 14 Pro simulator using Xcode 14.1.

Screenshot

import SwiftUI

@main
struct ExempleApp: App {
    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
        }
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            NavigationLink() {
                Text("The page is retained after returing from the main screen.")
            } label: {
                Text("This works")
            }
            
            TabView() {
                VStack {
                    NavigationLink() {
                        Text("The page doesn't stay after returing from the main screen.")
                    } label: {
                        Text("This doesn't work")
                    }
                }
                    .tabItem {
                        Image(systemName: "bookmark")
                    }
                    .tag(0)
            }
        }
    }
}

The NavigationLink inside the TabView should act like the normal one. Is this a bug or a feature?

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to the @AndrewCarter . I fixed the problem by replacing NavigationView with NavigationStack.

    Warning: NavigationStack only available in iOS16 and newer.


  2. This happens because you use a TabView inside of a NavigationView. This causes the problems that you have. I would suggest to let the tabview fill the whole page and let the NavigationView be part of it.

    import SwiftUI
    
    @main
    struct ExempleApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }
    
    struct ContentView: View {
        var body: some View {
            VStack {
                TabView {
                    NavigationView {
                        NavigationLink() {
                            Text("The page is retained after returing from the main screen.")
                        } label: {
                            Text("This works")
                        }
                        
                        VStack {
                            NavigationLink() {
                                Text("The page doesn't stay after returing from the main screen.")
                            } label: {
                                Text("This doesn't work")
                            }
                        }.tabItem {
                            Image(systemName: "bookmark")
                        }.tag(0)
                    }
                }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search