Home > database >  Preselect the first item in the NavigationList, but also display the content
Preselect the first item in the NavigationList, but also display the content

Time:07-30

I have a NavigationList in MacOS app. I want to preselect the first item when app opens but also to render the Navigation content. So far I am able to preselect the navigation list item, but not to render the view.

Code:

  • ContentView
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Board.timestamp, ascending: true)],
        animation: .default)
    private var boards: FetchedResults<Board>
    
    @State var selectedBoard: Board?

    var body: some View {
        NavigationView {
            List(boards, id: \.self, selection: $selectedBoard) { board in
                NavigationLink() {
                    BoardView(board: board)
                } label: {
                    Text(board.name!)
                }
            }
            .listStyle(.sidebar)
            .onAppear() {
                if (boards.first != nil) {
                    selectedBoard = boards.first
                }
            }
        }
       ...

Obviously, onAppear preselects the item in the list. But there is nothing on the right side:

screenshot

I have to click on the next item and then click back, and everything works.

What I am doing wrong?

CodePudding user response:

In general List's selection and NavigationLink are different things (that case that on user interaction they react both does not change the idea), they should be bound explicitly.

Try to bind links to the same selection, like

List(boards, id: \.self, selection: $selectedBoard) { board in
    NavigationLink(tag: board, selection: $selectedBoard) {     // << here !!
        BoardView(board: board)
    } label: {
        Text(board.name!)
    }
  • Related