Swiftui navigationLink macOS default/selected state

Thanks to this discussion, as a MacOS Beginner, I managed a very basic NavigationView with a list containing two NavigationLinks to choose between two views. I made it very basic to better understand. It might help other beginners. At start up it will be the first view that will be displayed. Just modify in ContentView.swift, self.selection = 0 by self.selection = 1 to start with the second view.

FirstView.swift

import SwiftUI

struct FirstView: View {

  var body: some View {
    Text("(1) Hello, I am the first view")
      .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct FirstView_Previews: PreviewProvider {
  static var previews: some View {
    FirstView()
  }
}

SecondView.swift

import SwiftUI

struct SecondView: View {
  var body: some View {
    Text("(2) Hello, I am the second View")
      .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct SecondView_Previews: PreviewProvider {
  static var previews: some View {
    SecondView()
  }
}

ContentView.swift

import SwiftUI

struct ContentView: View {

  @State var selection: Int?

  var body: some View {

    HStack() {

      NavigationView {
        List () {
          NavigationLink(destination: FirstView(), tag: 0, selection: self.$selection) {
            Text("Click Me To Display The First View")
          } // End Navigation Link

          NavigationLink(destination: SecondView(), tag: 1, selection: self.$selection) {
            Text("Click Me To Display The Second View")
          } // End Navigation Link

        } // End list
          .frame(minWidth: 350, maxWidth: 350)
        .onAppear {
            self.selection = 0
        }

      } // End NavigationView
        .listStyle(SidebarListStyle())
        .frame(maxWidth: .infinity, maxHeight: .infinity)

    } // End HStack
  } // End some View
} // End ContentView

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

Result:

enter image description here


working example. See how selection is initialized

import SwiftUI

struct Detail: View {
    let i: Int
    var body: some View {
        Text("\(self.i)").font(.system(size: 150)).frame(maxWidth: .infinity)
    }
}


struct ContentView: View {
    
    @State var selection: Int?
    var body: some View {
        
        HStack(alignment: .top) {
            NavigationView {
                List {
                    ForEach(0 ..< 10) { (i) in
                        
                        NavigationLink(destination: Detail(i: i), tag: i, selection: self.$selection) {
                            VStack {
                                Text("Row \(i)")
                                Divider()
                            }
                        }
                        
                    }.onAppear {
                        if self.selection != nil {
                            self.selection = 0
                        }
                    }
                }.frame(width: 100)
            }
        }.background(Color.init(NSColor.controlBackgroundColor))
    }
}

screenshot enter image description here


You can define a binding to the selected row and used a List reading this selection. You then initialise the selection to the first person in your person array.

Note that on macOS you do not use NavigationLink, instead you conditionally show the detail view with an if statement inside your NavigationView.

If person is not Identifiable you should add an id: \.self in the loop. This ressembles to:

struct PersonList: View {
  @Binding var selectedPerson: Person?

  var body: some View {
    List(persons, id: \.self, selection: $selectedPerson) { person in // persons is an array of persons
      PersonRow(person: person).tag(person)
    }
  }
}

Then in your main window:

struct ContentView: View {
  // First cell will be highlighted and selected
  @State private var selectedPerson: Person? = person[0]

  var body: some View {
    NavigationView {
      PersonList(selectedPerson: $selectedPerson)

      if selectedPerson != nil {
        PersonDetail(person: person!)
      }
    }
  }
}

Your struct person should be Hashable in order to be tagged in the list. If your type is simple enough, adding Hashable conformance should be sufficient:

struct Person: Hashable {
  var name: String
  // ...
}

There is a nice tutorial using the same principle here if you want a more complete example.