swift 如何使用iOS 16的NavigationStack的navigationDestination修饰符转到不同的视图?

mzsu5hc0  于 2023-02-28  发布在  Swift
关注(0)|答案(1)|浏览(223)

我尝试使用differnt navigationDestination修饰符从NavigationStack转到2个不同的视图,但是我总是被定向到相同的目的地。如何解决这个问题?
下面是我的代码:

import SwiftUI

struct NavTest: View {
    var body: some View {
        
        NavigationStack {
            NavigationLink("Link1", value: "Link-1")
            NavigationLink("Link2", value: "Link-2")
                
                .navigationDestination(for: String.self) {txtValue in Link1()}
                .navigationDestination(for: String.self) {txtValue in Link2()}
        }
    }
}

struct NavTest_Previews: PreviewProvider {
    static var previews: some View {
        NavTest()
    }
}

struct Link1: View {
    var body: some View{
        Text("You are in Link1 view")
    }
}

struct Link2: View {
    var body: some View{
        Text("You are in Link2 view")
    }
}

我知道我的两个导航链接都是字符串,所以也许这就是为什么我只重定向到第一个,但如何修改代码,使其在不同的视图中定向这两个链接?

nwlls2ji

nwlls2ji1#

.navigationDestination中,根据txtValue的值返回不同的视图。

.navigationDestination(for: String.self) { txtValue in
    if txtValue == "Link-1" {
        Link1()
    } else if txtValue ==  "Link-2" {
        Link2()
    }
}

但是,不要使用String s,而是尝试使用每个View都有一个case的枚举来进行编译时检查:

enum Route {
    case link1, link2
}

struct ContentView: View {
        
    var body: some View {
        
        NavigationStack {
            NavigationLink("Link1", value: Route.link1)
            NavigationLink("Link2", value: Route.link2)
                
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .link1:
                        Link1()
                    case .link2:
                        Link2()
                    }
                }
        }
    }
}

相关问题