首页 > 解决方案 > SwiftUI:如何在 MacOS 中用另一个视图替换视图

问题描述

当在 MacOS 上的 SwiftUI 中按下按钮时,我想用另一个视图替换一个视图(AppKit 不是 Catalyst)。

我试过这样的 NavigationLink

struct ContentView: View {
    var body: some View {
      NavigationView {
        NavigationLink( destination: Text("DESTINATIONVIEW").frame(maxWidth: .infinity, maxHeight: .infinity) ,
                              label: {Text("Next")} )
      }.frame(width: 500.0, height: 500.0)
  }
}

Destination View 的呈现方式与 iPadOS 中的一样,就像 Source View 的 Master-Detail Presentation 一样。我想要的是将 SourceView 替换为 Destination(几乎就像在 iOS 中一样)

另一种方法是使用 bool 变量切换呈现的视图

struct MasterList: View
{
  private let names = ["Frank", "John", "Tom", "Lisa"]

  @State var showDetail: Bool = false
  @State var selectedName: String = ""

  var body: some View
  {
    VStack
    {
      if (showDetail)
      { DetailViewReplace(showDetail:$showDetail, text: "\(selectedName)" )
      } else
      {
        List()
          {
            ForEach(names, id: \.self)
            { name in
              Button(action:
              {
                  self.showDetail.toggle()
                  self.selectedName = name
              })
              { Text("\(name)")}
                .buttonStyle( LinkButtonStyle() )
            }
        }.listStyle( SidebarListStyle())  
      }
    }
  }
}


struct DetailViewReplace: View {
  @Binding var showDetail: Bool
  let text: String

  var body: some View
  {
    VStack
    {
      Text(text)
     .frame(maxWidth: .infinity, maxHeight: .infinity)
      Button(action:
      { self.showDetail.toggle()
      })
      { Text("Return")
      }
    }
  }
}

但是,如果处理许多视图,这对我来说似乎很麻烦。

是否有最佳实践来做到这一点?

标签: macosswiftuiswiftui-navigationlink

解决方案


推荐阅读