5
votes

I’m trying to create a master/detail view with SwiftUI for a macOS app. The goal is to select an item in the side bar and have it change the main view accordingly. My code for this example is shown below:

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)

    }
}

When running the Mac app, the side bar selections can become inactive and sometimes popover views appear instead of changing the detail view. See below for a screen capture video of the issue. Is this a bug with SwiftUI NavigationView on the Mac or is there something I need to implement to make this work on macOS?

https://youtu.be/BF7m1OszZ5w

1

1 Answers

10
votes

As of Xcode 11.0 (11A420a) and macOS Catalina (19A558d) NavigationView works as expected:

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")
        }
    }
}

enter image description here