swiftuinavigationviewnavigationlinksidebarliststyle

SwiftUI: Select NavigationLink in a NavigationView / List with SidebarListStyle


I want to programmatically select a specific NavigationLink in a NavigationView / List.

The following code works fine on iPhones both in portrait or landscape mode == in situations where the List is not permanently visible besides its destination view.

enter image description here

Code:

struct ContentView: View {

private let listItems = [ListItem(), ListItem(), ListItem()]
@State var selection: Int? = 0

var body: some View {
    NavigationView {
        
        List(listItems.indices) {
            index in
            
            let item = listItems[index]
            let isSelected = (selection ?? -1) == index
            
            NavigationLink(destination: Text("Destination \(index)"),
                           tag: index,
                           selection: $selection) {
                
                Text("\(item.name) \(index) \(isSelected ? "selected" : "")")
                
            }
            
        }
    
    }
    .listStyle(SidebarListStyle())
    .onAppear(perform: {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
            selection = 2
        })
    })
    }

}


struct ListItem: Identifiable {
    var id = UUID()
    var name: String = "Some Item"
}

But it fails on iPads in landscape mode: While the navigation itself works (destination is shown correctly), the NavigationLink remains unselected.

ā†’ How can I select the NavigationLink in a way it appears selected on iPads too?


Solution

  • Here is possible approach. The idea is to programmatically activate navigation link via view model, but separate model-level selection and presentation (own by link) selection.

    Tested with Xcode 12b3 / iOS+iPadOS 14.

    class SelectionViewModel: ObservableObject {
        var currentRow: Int = -1 {
            didSet {
                self.selection = currentRow
            }
        }
    
        @Published var selection: Int? = nil
    }
    
    struct SidebarContentView: View {
    @StateObject var vm = SelectionViewModel()
    private let listItems = [ListItem(), ListItem(), ListItem()]
    
    var body: some View {
        NavigationView {
    
            List(listItems.indices) {
                index in
    
                let item = listItems[index]
                let isSelected = vm.currentRow == index
    
                Button("\(item.name) \(index) \(isSelected ? "selected" : "")") { vm.currentRow = index }
                .background (
                    NavigationLink(destination: Text("Destination \(index) selected: \(vm.currentRow)"),
                                   tag: index,
                                   selection: $vm.selection) {
                        EmptyView()
                    }.hidden()
                )
            }
    
        }
        .listStyle(SidebarListStyle())
        .onAppear(perform: {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
                vm.currentRow = 2
            })
        })
        }
    }