我最近一直在努力解决这个问题(用于表单的导航行组件),这对我有用:
@State private var shouldShowDestination = false
NavigationLink(destination: DestinationView(), isActive: $shouldShowDestination) {
Button("More info") {
self.shouldShowDestination = true
}
}
只需将Button 与NavigationLink 包装起来,即可通过按钮控制激活。
现在,如果您要在同一个视图中有多个按钮+链接,而不是为每个激活 State 属性,您应该依赖此初始化程序
/// Creates an instance that presents `destination` when `selection` is set
/// to `tag`.
public init<V>(destination: Destination, tag: V, selection: Binding<V?>, @ViewBuilder label: () -> Label) where V : Hashable
https://developer.apple.com/documentation/swiftui/navigationlink/3364637-init
按照这个例子的思路:
struct ContentView: View {
@State private var selection: String? = nil
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Second View"), tag: "Second", selection: $selection) {
Button("Tap to show second") {
self.selection = "Second"
}
}
NavigationLink(destination: Text("Third View"), tag: "Third", selection: $selection) {
Button("Tap to show third") {
self.selection = "Third"
}
}
}
.navigationBarTitle("Navigation")
}
}
}
更多信息(以及上面稍作修改的示例)取自 https://www.hackingwithswift.com/articles/216/complete-guide-to-navigationview-in-swiftui(在“程序化导航”下)。
或者,创建一个自定义视图组件(嵌入NavigationLink),例如这个
struct FormNavigationRow<Destination: View>: View {
let title: String
let destination: Destination
var body: some View {
NavigationLink(destination: destination, isActive: $shouldShowDestination) {
Button(title) {
self.shouldShowDestination = true
}
}
}
// MARK: Private
@State private var shouldShowDestination = false
}
并将其作为Form(或List)的一部分重复使用:
Form {
FormNavigationRow(title: "One", destination: Text("1"))
FormNavigationRow(title: "Two", destination: Text("2"))
FormNavigationRow(title: "Three", destination: Text("3"))
}