Skip to content

Instantly share code, notes, and snippets.

@leonspok
Last active February 15, 2020 19:12
Show Gist options
  • Save leonspok/fe57e1e9403dd83f9882f908f5ea0e43 to your computer and use it in GitHub Desktop.
Save leonspok/fe57e1e9403dd83f9882f908f5ea0e43 to your computer and use it in GitHub Desktop.
SwiftUI manage navigation bar visibility in navigation stack
import SwiftUI
final class NavBarVisibility: ObservableObject {
@Published var isHidden: Bool
init(isHidden: Bool) {
self.isHidden = isHidden
}
}
struct ContentView: View {
var body: some View {
NavigationView {
A()
}
.environmentObject(NavBarVisibility(isHidden: false))
}
}
struct A: View {
@EnvironmentObject var navBarVisibility: NavBarVisibility
var body: some View {
VStack(spacing: 20) {
NavigationLink(destination: B()) {
Text("Go to screen B")
}
Text("Navigation bar should be hidden")
}
.onAppear(perform: {
self.navBarVisibility.isHidden = true
})
.navigationBarTitle("A")
.navigationBarHidden(self.navBarVisibility.isHidden)
}
}
struct B: View {
@EnvironmentObject var navBarVisibility: NavBarVisibility
var body: some View {
Text("Navigation bar should not be hidden")
.onAppear(perform: {
self.navBarVisibility.isHidden = false
})
.navigationBarTitle("B")
.navigationBarHidden(self.navBarVisibility.isHidden)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment