• Tags: swiftui
  • Vladimirs Nordholm

SwiftUI iOS List default selection with NavigationSplitView

Introduction

Looking through Apple’s documentation, I found no clear example of how to set a default selected option for a List in a NavigationSplitView.

This post shows how to the the default selected option in a list, and how to best interact with a split view.

Example

Clear example of how to set a default selected option for a sidebar List in a NavigationSplitView.

@State private var selectedId: String? = "banana"

NavigationSplitView {

  List(selection: $selectedId) {

    NavigationLink(value: "apple") {
      Text("Apple")
    }

    NavigationLink(value: "banana") {
      Text("Banana")
    }

  }
} detail: {
  Text("\(selectedId ?? "Nothing selected")")
}

We use "NavigationLink" with a "value:" parameter instead of navigating to a new view, and keep track of the selection in "selectedId"; the “selected” value must be optional for iOS [1].

We do not specify a destination view in the link – instead we use the "detail:" to update the data in its view.

Using custom data

Models can also be used to display custom data, as long as the type conforms to Decodable, Encodable, and Hashable [2].

@State var selected: Fruit?

NavigationSplitView {
  …
} detail: {
  if let selected {
    FruitDetail(selected)
  } else {
    Text("Nothing selected")
  }
}

NOTE: Setting the value of a "NavigationLink" to "nil" will disable the link.

References

[1]
Apple Inc., "NavigationLink", Apple Developer Documentation
[2]
Apple Inc., "NavigationLink – init:(value:label:)", Apple Developer Documentation