在 SwiftUI 中有多个导航视图时隐藏导航栏 [英] Hiding Navigation Bar in case of multiple Navigation Views in SwiftUI

查看:55
本文介绍了在 SwiftUI 中有多个导航视图时隐藏导航栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有多个导航视图,我无法隐藏导航栏.我希望导航栏出现在第一个和第二个屏幕上,但不在第三个屏幕上.

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 :(

推荐答案

如果您想在第三个视图中完全隐藏导航栏,这里是一种可行的方法.(注意:顺便说一句,在一个视图层次结构中必须只有一个 NavigationView,所以第三视图中不需要另一个)

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)

使用 Xcode 11.4/iOS 13.4 测试

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
            }
    }
}

这篇关于在 SwiftUI 中有多个导航视图时隐藏导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆