There is a problem that the selection value is initialized when NavigationSplitView operates on the iPad.

  1. Run the attached source on the iPad.
  2. Rotate your iPad in landscape orientation.
  3. Select one of 1,2,3 from the list on the left.
  4. Press the Home button to exit to the home screen.
  • You can check that the "selectedID" value is initialized after the app enters the background state.
  1. When I go back to the app I was running, the selected row in the list is cancelled.

  2. Proceed with the same action once more.

  • In the second process, the "selectedID" value is not initialized.

The "selectedID" value is always initialized on the first run. I would like to know how to deal with this problem.

import SwiftUI

struct ContentView: View {
    
    @Environment(\.scenePhase) var scenePhase
    @State var selectedID: UUID?
    let profiles = [Profile(name: "1"), Profile(name: "2"), Profile(name: "3")]
    
    var body: some View {
        NavigationSplitView {
            List(profiles, id: \.id, selection: $selectedID) { profile in
                NavigationLink(value: profile.id) {
                    Text(profile.name)
                }
            }
        } detail: {
            Text(selectedID?.uuidString ?? "nil")
        }
        .task(id: selectedID) {
            print("Selection changed to \(selectedID?.uuidString ?? "nil")")
        }
        .onChange(of: scenePhase) { newPhase in
            if newPhase == .active {
                print("Active :", selectedID ?? "nil")
            } else if newPhase == .inactive {
                print("Inactive :", selectedID ?? "nil")
            } else if newPhase == .background {
                print("Background :", selectedID ?? "nil")
            }
        }
    }
}

struct Profile: Identifiable, Hashable {
    let id = UUID()
    let name: String
}
There is a problem that the selection value is initialized when NavigationSplitView operates on the iPad.
 
 
Q