首页 > 解决方案 > 导航栏隐藏在 SwiftUI 中不起作用

问题描述

我有三观。我想在第三个视图中隐藏导航栏。即使我给.navigationBarHidden(true)导航栏显示!

我找不到我做错的地方。我附上了我的代码和下面的截图。

Xcode 版本 - 11.1

struct ContentViewOne: View {
    var body: some View {
        NavigationView {
            ZStack {
                
                Color.yellow.edgesIgnoringSafeArea(.all)
                VStack(spacing: 20) {
                    Text("View One")
                    
                    NavigationLink(destination: ContentViewTwo()) {
                        Text("Navigate to View Two")
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.red)
                    }
                }
            }
            .navigationBarTitle("View One")
        }
    }
}

struct ContentViewTwo: View {
    var body: some View {
        
        ZStack {
            Color.green.edgesIgnoringSafeArea(.all)
            VStack(spacing: 20) {
                Text("View Two")
                NavigationLink(destination: ContentViewThree()) {
                    Text("Navigate to View Three")
                        .foregroundColor(.white)
                        .padding()
                        .background(Color.red)
                }
            }
        }
        .navigationBarTitle("View Two")
    }
}

struct ContentViewThree: View {
    var body: some View {
        ZStack {
            Color.gray.edgesIgnoringSafeArea(.all)
            Text("View Three")
        }
        .navigationBarTitle("View Three")
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)
    }
}

在此处输入图像描述

标签: iosswiftswiftui

解决方案


注意:(由于某些原因,它在某些情况下有效)SwiftUI需要您.navigationBarTitle才能.navigationBarHidden正常工作。

NavigationView {
    ScrollView() {
     ......
    }.  
    .navigationBarTitle("") //this must be empty
    .navigationBarHidden(true)
    .navigationBarBackButtonHidden(true)
}

推荐阅读