iOS16-如何浏览具有可选值的隐藏链接



我以前使用了一个可选值来单击隐藏链接以在我的应用程序中导航。类似Swift破解中的例子:

@State private var selection: String? = nil
var body: some View {
....
NavigationLink(destination: Text("View A"), tag: "A", selection: $selection) { EmptyView() }
NavigationLink(destination: Text("View B"), tag: "B", selection: $selection) { EmptyView() }
Button("Tap to show A") {
selection = "A"
}
Button("Tap to show B") {
selection = "B"
}

对于iOS 16,这是不推荐使用的。我目前正在设置一个可选值,当它不是零时,我希望打开一个链接。我不知道如何使用新的NavigationLink/Value/Destination组合。其他人想好怎么做了吗?

我创建了一个新项目,并将ContentView切换到以下内容:

private enum Destinations: Hashable {
case empty
case general
case myQuestionView(String)
}
struct ContentView: View {
@State private var selection: Destinations?

@State private var mySelectedString: String?

var body: some View {

NavigationSplitView {
List(selection: $selection) {
NavigationLink(value: Destinations.general) {
Text("Example")
}
if mySelectedString != nil {
NavigationLink(value: Destinations.myQuestionView(mySelectedString!)) {
Text("String: (mySelectedString ?? "no name")")
}
}
Button(action: {
mySelectedString = "A Name"
}, label: {
Text("Set the value")
})
}
} detail: {
NavigationStack {
switch selection ?? .empty {
case .empty: Text("Please select an option to continue.")
case .general: Text("Result of this option")
case .myQuestionView(let aString): Text("Hello (aString)")
}

}
}
}
}

这里的Set the value按钮设置selectedString,使链接出现,但我不能使它自动导航AND,理想情况下,它永远不会出现,并且在设置值时会导航。

好的。。。答案非常简单,留下问题和这个答案,以防对其他人有帮助。

您不需要有一个不可见的NavigationLink。您只需要将选择设置为新的目的地:selection = .myQuestionView("this name instead")。或者,如果我使用的是导航路径NavigationStack(path: $myPath),我只会附加它。

因此,在这个特定的例子中,ContentView现在是:

private enum Destinations: Hashable {
case empty
case general
case myQuestionView(String)
}
struct ContentView: View {
@State private var selection: Destinations?
var body: some View {

NavigationSplitView {
List(selection: $selection) {
NavigationLink(value: Destinations.general) {
Text("Example")
}
Button(action: {
selection = .myQuestionView("this name instead")
}, label: {
Text("Set the value")
})
}
} detail: {
NavigationStack {
switch selection ?? .empty {
case .empty: Text("Please select an option to continue.")
case .general: Text("Result of this option")
case .myQuestionView(let aString): Text("Hello (aString)")
}

}
}
}
}

最新更新