如何以编程方式触发 NavigationLink?

Hei*_*ann 7 swiftui

我有一个带有一堆 NavigationLinks 的 NavigationView。当用户点击“添加”按钮时,我想在视图中创建一个新项目并自动将它们发送给它。我可以这样做吗?

Pra*_*tti 1

SwiftUI当其真实来源发生变化时会触发View更改(the body),因此您只需更改该Binding<Bool>值即可触发视图更新。存储每个链接的绑定,并在单击按钮时更改其值。

假设您想要推行三种不同的观点。然后您将需要存储三个不同的绑定。您可以将这些绑定存储为三个单独的@State属性,或使用@StateObject视图模型,如下所示:

class RootViewModel: ObservableObject {
  @Published var isLinkActive:[Int: Bool] = [:]
}

struct RootView: View {
  @StateObject var viewModel = RootViewModel()
  ...
  func binding(index: Int) -> Binding<Bool> {
    return .init(get: { () -> Bool in
      return self.viewModel.isLinkActive[index, default: false]
    }) { (value) in
      self.viewModel.isLinkActive[index] = value
    }
  }
  ...
  func destination(index: Int) -> some View {
    switch index {
      case 1:
        return ContentViewOne()
      case 2:
        return ContentViewTwo()
      case 3:
        return ContentViewThree()
      default:
        return EmptyView()
    }
  }
  
  var body: some View {
    return
      NavigationView {
        VStack {
          ForEach(1..<4) { index in
            NavigationLink(destination: self.destination(index: index), isActive: self.binding(index: index)) {
              Text("Link to Content View \(index)")
            }
          }
          Button("Add") {
            self.contentViewModel.isLinkActive[2] = true // Change this index depending on which view you want to push.
          }
        }
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

所以这里的按钮模拟了第二次NavigationLink点击。我曾经在推动过程中StateObject停止重新绘制整体。RootView