问题
I am having trouble hiding the navigation bar in case of multiple navigation views. I want navigation bars to be present on first and second screen but not on the third one.
struct FirstView: View {
init() {
UINavigationBar.appearance().backgroundColor = UIColor.green
}
var body: some View {
NavigationView {
NavigationLink(destination: SecondView()) {
Text("Second View")
}.navigationBarTitle("First View")
}
}
}
// Second View
struct SecondView: View {
var body: some View {
NavigationLink(destination: ThirdView()) {
Text("Third View")
}
}
}
// Third View
struct ThirdView: View {
var body: some View {
Text("Welcome")
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
I tried hiding the navigation bar on third screen with the above code, but it doesn't work :(
回答1:
If you want to hide navigation bar completely at third view here is possible approach. (Note: btw in one view hierarchy there must be only one NavigationView, so another one in ThirdView is not needed)
Tested with Xcode 11.4 / iOS 13.4
class HideBarViewModel: ObservableObject {
@Published var isHidden = false
}
struct FirstView: View {
@ObservedObject var vm = HideBarViewModel()
init() {
UINavigationBar.appearance().backgroundColor = UIColor.green
}
var body: some View {
NavigationView {
NavigationLink(destination: SecondView()) {
Text("Second View")
}.navigationBarTitle("First View")
.navigationBarHidden(vm.isHidden)
}.environmentObject(vm)
}
}
// Second View
struct SecondView: View {
var body: some View {
NavigationLink(destination: ThirdView()) {
Text("Third View")
}
}
}
// Third View
struct ThirdView: View {
@EnvironmentObject var vm: HideBarViewModel
var body: some View {
Text("Welcome")
.onAppear {
self.vm.isHidden = true
}
}
}
来源:https://stackoverflow.com/questions/62656831/hiding-navigation-bar-in-case-of-multiple-navigation-views-in-swiftui