SwiftUI: Preselected NavigationLink on launch in 3 column not highlighted

Viewed 39

I have a 3 column NavigationView similar to Apple's Mail app and I would like to preselect the "Inbox" row on the SidebarView on launch.

My current implementation has no problem selecting the desired mailbox on launch, but the preselected mailbox is not highlighted when the sidebar is shown.

enum Mailbox: String, Identifiable {
    var id: Mailbox {self}
    case inbox, draft, sent
}

struct MainView: View {
    
    @State private var selection: Mailbox? = Mailbox.inbox
    
    var body: some View {
        NavigationView {
            SidebarView(selection: $selection)
            ListView(mailbox: selection)
            DetailView()
        }
    }
}

struct SidebarView: View {
    
    var mailboxes: [Mailbox] = [
        .inbox,
        .draft,
        .sent
    ]
    
    @Binding var selection: Mailbox?
    
    var body: some View {
        List(selection: $selection) {
            Section(header: Text("Mailbox")) {
                ForEach(mailboxes) { mailbox in
                    NavigationLink(destination: ListView(mailbox: mailbox),
                                   tag: mailbox,
                                   selection: $selection) {
                        Text(mailbox.rawValue.capitalized)
                    }
                }
            }
        }
        .navigationTitle(Text("Mail"))
        .listStyle(SidebarListStyle())
    }
}

struct ListView: View {
    var mailbox: Mailbox?
    
    var body: some View {
        List {
            ForEach (0..<30) { i in
                NavigationLink(destination: DetailView(number: i)) {
                    Text("\(mailbox?.rawValue.capitalized ?? "") mail \(i)")
                }
            }
        }
        .listStyle(InsetGroupedListStyle())
        .navigationTitle(Text(mailbox?.rawValue.capitalized ?? ""))
    }
}

struct DetailView: View {
    var number: Int? = nil
    
    var body: some View {
        if let number = number {
            Text("Detail View \(number)")
        } else {
            Text("Select a mail to view")
        }
    }
}

Result: enter image description here

Desired result: enter image description here

0 Answers
Related