4

For some reason, a List will reset its selection to nil when the app is in the background.

Steps to reproduce the issue:

  • Run attached sample project
  • Once the app has launched, select a name in the sidebar
  • Move the app to the background
  • Wait a few seconds
  • Bring back the app to the foreground

Expected result:

The list selection should still be valid

Actual result:

The list selection is set to nil

Notes:

I’m using a StateObject, which should be the way to ensure that data isn’t regenerated when views are rendered. Is this a bug or something else needs to be taken care of?

class AppModel: ObservableObject {
    @Published var selectedPerson: Person?
}


@main

struct NilListSelectionApp: App {
    @StateObject var appModel = AppModel()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appModel)
        }
    }
}
struct Person: Identifiable, Hashable {
    let id: UUID
    let firstname: String

    init(firstname: String) {
        id = UUID()
        self.firstname = firstname
    }
}


struct ContentView: View {
    @EnvironmentObject private var appModel: AppModel

    var body: some View {
        NavigationSplitView {
            SidebarView()
        } detail: {
            PersonView(person: appModel.selectedPerson)
        }
    }
}


struct SidebarView: View {
    @EnvironmentObject private var appModel: AppModel

    private let persons = [Person(firstname: "Joe"), Person(firstname: "Jane")]

    var body: some View {
        List(persons, id:\.self, selection: $appModel.selectedPerson) { person in
            Text(person.firstname).tag(person)
        }
        .listStyle(.sidebar)
    }
}


struct PersonView: View {
    let person: Person?

    var body: some View {
        if let person {
            Text(person.firstname)
        }
        else {
            Text("No Selection")
        }
    }
}
GSD
  • 149
  • 6

0 Answers0