'Swiftui navigationLink macOS default/selected state

I build a macOS app in swiftui

i try to create a listview where the first item is preselected. i tried it with the 'selected' state of the navigationLink but it didn't work.

Im pretty much clueless and hope you guys can help me.

The code for creating this list view looks like this.

//personList
struct PersonList: View {
    var body: some View {
          NavigationView
          {
            List(personData) { person in
                NavigationLink(destination: PersonDetail(person: person))
                {
                    PersonRow(person: person)
                }
            }.frame(minWidth: 300, maxWidth: 300)
          }
    }
}

(Other views at the bottom)

This is the normal View when i open the app. appnormalstate When i click on an item its open like this. Thats the state i want as default opening state when i render this view. appwantedstate

The Code for this view looks like this:

//PersonRow

struct PersonRow: View {

    //variables definied
    var person: Person

    var body: some View {

        HStack
        {
            person.image.resizable().frame(width:50, height:50)
                .cornerRadius(25)
                .padding(5)

            VStack (alignment: .leading)
            {
                Text(person.firstName + " " + person.lastName)
                    .fontWeight(.bold)
                    .padding(5)
                Text(person.nickname)
                    .padding(5)
            }
            Spacer()
        }
    }
}


//personDetail

struct PersonDetail: View {

    var person : Person

    var body: some View {

        VStack
        {
              HStack
              {
                VStack
                {
                    CircleImage(image: person.image)
                    Text(person.firstName + " " + person.lastName)
                      .font(.title)
                    Text("Turtle Rock")
                      .font(.subheadline)
                }
                Spacer()
                Text("Subtitle")
                  .font(.subheadline)
            }
            Spacer()
        }
        .padding()
    }
}

Thanks in advance!



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

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

Solution 4:[4]

import SwiftUI


struct User: Identifiable {
    let id: Int
    let name: String
}

struct ContentView: View {
    
    @State private var users: [User] = (1...10).map { User(id: $0, name: "user \($0)")}
    @State private var selection: User.ID?
    
    var body: some View {
        NavigationView {
            List(users) { user in
                NavigationLink(tag: user.id, selection: $selection) {
                    Text("\(user.name)'s DetailView")
                } label: {
                    Text(user.name)
                }
            }
            
            Text("Select one")
        }
        .onAppear {
            if let selection = users.first?.ID {
                self.selection = selection
            }
        }
    }
}

You can use make the default selection using onAppear (see above).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alexander Volkov
Solution 3 Wild8x
Solution 4 radley