Reputation: 318
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:
If I set navigation bar title of the UIHostingController to "", then there will be no "<Back" but "<".
If I set navigation bar title of the UIHostingController to "Back", then after coming back View1 will show "Back" in the middle of the navigation bar.
If I hide the navigation bar at first, then "Exit" button will not be shown.
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
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