我正在尝试使用SwiftUI为macOS应用创建主视图/详细视图。目的是在侧栏中选择一个项目,并使其相应地更改主视图。我的示例代码如下所示:
import SwiftUI
struct MyMasterView: View {
let names = ["Homer", "Marge", "Bart", "Lisa"]
var body: some View {
List {
ForEach(names, id: \.self) { name in
NavigationLink(name, destination: MyDetailView(name: name))
}
}
.frame(width: 150, height: 300)
}
}
struct MyDetailView: View {
var name = "Name"
var body: some View {
HStack {
Text("Hello \(name)")
.font(.largeTitle)
}
.frame(width: 450, height: 300)
}
}
struct ContentView: View {
var body: some View {
NavigationView {
MyMasterView()
MyDetailView()
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.frame(width: 600, height: 300)
}
}
运行Mac应用程序时,侧栏选择可能会变得无效,并且有时会出现弹出视图,而不是更改详细视图。有关该问题的屏幕截图,请参见下文。这是Mac上的SwiftUI NavigationView的错误,还是我需要实现某些功能才能在macOS上实现此功能?
答案 0 :(得分:4)
从Xcode 11.0(11A420a)和macOS Catalina(19A558d)开始,NavigationView可以按预期工作:
import SwiftUI
struct DetailView: View {
let text: String
var body: some View {
Text(text)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView: View {
private let names = ["Homer", "Marge", "Bart", "Lisa"]
@State private var selection: String?
var body: some View {
NavigationView {
List(selection: $selection) {
Section(header: Text("The Simpsons")) {
ForEach(names, id: \.self) { name in
NavigationLink(destination: DetailView(text: name)) {
Text(name)
}
}
}
}.listStyle(SidebarListStyle())
DetailView(text: "Make a selection")
}
}
}