Hubert Rzeminski
Hubert Rzeminski

Reputation: 469

SwiftUI navigation link back button working in preview but not in simulator or device

Im trying to use a simple navigation view, with a navigation link to a different view. When running the app and the navigation link is pressed it takes me to the new view.

However when I'm on a simulator or device the back button dose not work, whereas on the preview it works fine.

Any ideas what the problem may be?


import SwiftUI

struct HomeView: View {
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: Text("Detail View")) {
                    Text("Hello World")
                }
            }
            .navigationBarTitle("SwiftUI")
        }
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}

I think the problem may be caused by the fact that the HomeView is part of a tabView. The following code is from AppView.swift which is what is run when the app is run (You can see the code for that at the very bottom).

I think this is the problem because when the code bellow is commented out the app works fine.


HomeView()
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
.onTapGesture {
self.selectedTab = 2
}
.tag(2)
                    
@main
struct Skate_AppApp: App {
    var body: some Scene {
        WindowGroup {
            HomeView()
        }
    }
}

Upvotes: 2

Views: 2357

Answers (1)

Cod3rMax
Cod3rMax

Reputation: 958

From your code I can tell that the problem is in onTapGesture, and I presume from self.selectedTab = 2 that you want to get which tab the user has selected.

Let's refactor your code a little bit with the same concept.

Solution: Delete onTapGesture and add onAppear.

    TabView {
        
        HomeView().tabItem {
                Image(systemName: "house.fill")
                Text("Home")
        }.onAppear{
            self.selectedTab = 2
        }.tag(2)
        
        AnotherView().tabItem {
                Image(systemName: "car.fill")
                Text("Login View")
        }.onAppear{
            self.selectedTab = 3
        }.tag(3)
        
    }

By this whenever a view appears, it means that the user has selected it, onAppear will be called, and your variable selectedTab will be changed. I hope this answer your question.

Upvotes: 8

Related Questions