Home > Mobile >  Save SwiftUI List selection using @AppStorage in a Mac app
Save SwiftUI List selection using @AppStorage in a Mac app

Time:10-05

In a Mac app, I'm trying to store a SwiftUI List selection using AppStorage. The goal is to have the app remember the last selection such that it is selected when the app restarts. I can't figure out how to bind the selection to the AppStorage property. Any suggestions on how to accomplish this?

enum Fruit: String, CaseIterable, Identifiable {
    case apple
    case orange
    case mango
    case lemon
    var id: String { rawValue }
}

struct Sidebar: View {

    @Binding var selection: Fruit

    var body: some View {
        List(Fruit.allCases, id: \.self, selection: $selection) { fruit in
            Text(fruit.rawValue)
        }
        .listStyle(SidebarListStyle())
        .frame(minWidth: 150)
    }
}

struct DetailView: View {

    var selection: Fruit

    var body: some View {
        switch selection {
        case .apple:
            Text("           
  • Related