hbr4u7vb2sljksdf2
hbr4u7vb2sljksdf2

Reputation: 318

Navigation bar: "hide" title but keep it for the subsequent back button

In my app I have two SwiftUI views, let's call them View1 and View2. View1 is started as a UIHostingController and has a "Go to View2" button which pushes View2 on the navigation controller of the mentioned UIHostingController (no SwiftUI Navigation Links etc). View1 has to display the navigation bar because it has a custom "Exit" button in the toolbar. View2 should show "<Back" navigation bar button which leads to the View1.

Problem:

So, to sum up, what I need is: View1 shows navigation bar only with the "Exit" toolbar button, no title. View2 shows only "<Back" navigation bar button

How can I achieve it ?

Note: the whole navigation logic is done with UIKit. View1 notifies the view model which calls a delegate which pushes View2 on the navigation stack. There are no SwiftUI navigation links etc.

Upvotes: 2

Views: 694

Answers (1)

Wouter
Wouter

Reputation: 151

You might want consider a hidden Navigation Link so you get the push behaviour you are looking for. This will leave you with the following views;

struct View1: View {
    @State private var isActive = false

    var body: some View {
        NavigationView {
            VStack {
                Button("Present") {
                    isActive = true
                }

                NavigationLink(destination: View2(), isActive: $isActive) {
                    EmptyView()
                }.hidden()
            }.toolbar(content: {
                Button("Exit") {
                    print("Exit view")
                }
            })
        }
    }
}
struct View2: View {
    var body: some View {
        NavigationView {
            Text("View 2")
        }
    }
}

Your first view will use the button to present view 2 through a push animation. Giving you the back button behaviour you are looking for. Your first view will have no title and a exit button in the toolbar in the right top corner.

Upvotes: 1

Related Questions