ios 如何在NavigationStack之外使用NavigationLink?

os8fio9y  于 2023-01-18  发布在  iOS
关注(0)|答案(1)|浏览(156)

我在NavigationStack上放置了一个安全区域的插入视图,作为所有压入视图的底栏。但是,在安全区域的插入视图中,有一些按钮我想将视图压入堆栈。NavigationLink是灰色的,因为它在NavigationStack之外。
下面是我的代码:

NavigationStack {
    VStack {
        Image(systemName: "globe")
        Text("Hello, world!")
    }
    .toolbar {
        ToolbarItem(placement: .navigationBarLeading) {
            NavigationLink("Button 1") {
                Text("Screen 1")
            }
        }
        ToolbarItem(placement: .navigationBarTrailing) {
            NavigationLink("Button 2") {
                Text("Screen 2")
            }
        }
    }
}
.safeAreaInset(edge: .bottom, spacing: 0) {
    HStack {
        NavigationLink("Button 1") {
            Text("Screen 1")
        }
        .frame(minWidth: 0, maxWidth: .infinity)
        NavigationLink("Button 2") {
            Text("Screen 2")
        }
        .frame(minWidth: 0, maxWidth: .infinity)
    }
    .padding()
    .background(.regularMaterial)
}

它的行为方式是,底部视图确实在所有推送的视图中保持不变,但那里的按钮不做任何事情(顶部导航栏中的按钮工作正常):

如何将底部安全区域中的按钮插入以导航到不同的屏幕,同时仍将其保持在NavigationStack级别,因为我不想将此底部覆盖代码放置在每个子视图上?

wfveoks0

wfveoks01#

您可以通过NavigationStack使用编程导航:
状态变量navigationPath保存活动路径,您可以使用NavigationLink(value:)或直接设置它(如在安全区域按钮中)来更改它。

struct ContentView: View {
    
    // holds the active navigation path
    @State private var navigationPath: [Int] = []
    
    var body: some View {
        
        NavigationStack(path: $navigationPath ) {
            VStack {
                Image(systemName: "globe")
                Text("Hello, world!")
            }
            // defines destinations of path
            .navigationDestination(for: Int.self, destination: { value in
                switch value {
                case 1: Text("Screen 1")
                case 2: Text("Screen 2")
                default: Text("unknown view")
                }
            })
            
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    NavigationLink("Button 1", value: 1)
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    NavigationLink("Button 2", value: 2)
                }
            }
        }
        
        .safeAreaInset(edge: .bottom, spacing: 0) {
            HStack {
                Button("Button 1") {
                    navigationPath = [1]
                    // or if you want to extend the path:
                    // navigationPath.append(1)
                }
                .frame(maxWidth: .infinity)
                Button("Button 2") {
                    navigationPath = [2]
                    // or if you want to extend the path:
                    // navigationPath.append(2)
               }
                .frame(maxWidth: .infinity)
            }
            .padding()
            .background(.regularMaterial)
        }
    }
}

相关问题