What is the alternative for SwiftUI of UIKit's "pushViewController" in a barButtonItem

Viewed 4801

I'm working on a very simple app in SwiftUI and I have managed to create a NavigationButton for my List that takes me to the DetailViewController. In the up right corner I wanted to have a "+" button to add things to my List:

navigationBarItems(trailing:
                    NavigationButton(destination: DetailVC()) {
                        Image(systemName: "plus")
                            .resizable()
                            .frame(width: 20, height: 20)
                    }
)

The problem is that when I tap on the button it doesn't navigate to my DetailVC.

I also tried this:

.navigationBarItems(trailing:
                    PresentationButton(destination: DetailVC()) {
                        Image(systemName: "plus")
                            .resizable()
                            .frame(width: 20, height: 20)
                    }
)

With this code the problem is that it doesn't present the DetailVC with a "Back" button, but it shows up from the bottom and there is no way to go back in my ContentView

What is the correct item to put in the navigation bar to navigate correctly?

Thank you, Nico

3 Answers

In SwiftUI you use a NavigationButton to navigate your app.

Just replace your PresentationButton with a NavigationButton:

.navigationBarItems(trailing:
    NavigationButton(destination: DetailVC()) {
        Image(systemName: "plus")
            .resizable()
            .frame(width: 20, height: 20)
    }
)

Apple Docs:

https://developer.apple.com/documentation/swiftui/navigationbutton (deprecated)

EDIT:


The NavigationButton was deprecated, so it should no longer be used.

Instead there is a NavigationLink view, which should work. This struct is new and I wasn't able to test it yet but the code for the button itself should look like this:

NavigationLink(destination: DetailVC()) { }

Apple Docs:

https://developer.apple.com/documentation/swiftui/navigationlink

I made sample to display list and details. Hope this sample app will help you.

https://github.com/Shiju86/ListViewSwiftUI

and that's right, NavigationButton is no more and instead of this apple provide us NaviagtionLink.

NavigationLink should be how do do this. However in iOS 13.2 and 13.3 this appears to be broken/unreliable when used within a header (and completely broke my app: I figured out a work around by moving the NavigationLink out of the header and making the something else a modal).

It works better (but still with quirks) within standard Views themselves. Ridiculously you may want to consider using a modal instead of child View as that seems to actually work.

Related