Show Another Screen From Different Places

SwiftUI changed how navigation is performed and instead of creating a controller and presenting it you just use NavigationLink to show another screen.

Let’s create a standard layout, one button that on tap shows another screen with Text view.

NavigationView {
    
NavigationLink(destination: Text(“Second screen”)) {
    
    Text(“Click me”)
    }
}

It does something you expect.

However, NavigationLink has one more interesting parameter called isActive.

You don’t need to tap on the content of NavigationLink to show another screen, you can just change this flag.

Create state property that keeps information if the second screen is shown.

@State private var showingSecondScreen = false

Now add isActive to NavigationLink as the last parameter.

NavigationLink(destination: Text(“Second screen”), isActive: $showingSecondScreen) {
    
Text(“Click me”)
}

Since now, every time showingSecondScreen is true the second screen is shown, when it’s false it isn’t.

Let’s add Image with one tap gesture to change this flag on every tap on true.

Image(systemName: “star”)
    .
onTapGesture {
    
    showingSecondScreen = true
}

On every tap on this star image, you’ll be moved to the second screen.

The second screen is bound with this flag. You can add onDisappear for Image and you’ll be moved back and forward on each tap.

Image(systemName: “star”)
.
onTapGesture {
    
showingSecondScreen = true
}
.
onDisappear(perform: {
    
showingSecondScreen = false
})

On each tap, you’ll be moved to the second screen and immediately back to the first screen.