swiftui

Picker doesn't show selected value


I'm creating a test app for selecting a value in a filtersheet. Below I put the code I use.

The problem is that the selected value in the picker isn't shown. This happens when I use a Binding and not when using State. I want to use the Binding because the selected value has to be used in the calling view.

struct ContentView: View {
    @StateObject var contentListViewModel = ContentListViewModel()
    
    var body: some View {
        NavigationStack {
            VStack {
                Text(contentListViewModel.selectedNumber?.uuidString ?? "No selection")
                    .font(.system(size: 12))
                VStack() {
                    NavigationLink("Person to tap") {
                        HStack {
                            Text("Person")
                                .frame(width: 100, alignment: .leading)
                            Image(systemName: "person.circle")
                        }
                    }
                    .navigationTitle("Person")
                    
                    Spacer()
                }
            }
            .navigationTitle("Show Filter Sheet")
            .navigationBarTitleDisplayMode(.automatic)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button(action: {
                        contentListViewModel.showFilterScreen.toggle()
                    }, label: {
                        VStack {
                            Text("Filter")
                                .font(.system(size: 12))
                            Image(systemName: "line.3.horizontal")
                                .resizable()
                        }
                    })
                    .fullScreenCover(isPresented: $contentListViewModel.showFilterScreen, onDismiss: {
                        print("Sheet has been dismissed.")
                    }) {
                        FilterSheet(selectedNumber: $contentListViewModel.selectedNumber)
                    }
                }
            }
        }
    }
}

class ContentListViewModel: ObservableObject {
    @Published var showFilterScreen: Bool = false
    
    @Published var selectedNumber: PickerOneNumber.ID?
}

The filterscreen looks like:

struct FilterSheet: View {
    @Environment(\.dismiss) var dismiss
    
    @Binding var selectedNumber: PickerOneNumber.ID?
    
    @State private var selectedNumber_2: PickerOneNumber.ID?
    
    let numbers: [PickerOneNumber] = [
        .init(number: 1),
        .init(number: 2),
        .init(number: 3)
    ]
    
    init(selectedNumber: Binding<PickerOneNumber.ID?>) {
        self._selectedNumber = selectedNumber
    }
    
    var body: some View {
        VStack {
            HStack {
                Picker("Select number", selection: $selectedNumber) {
                    Text("Make selection ...").tag(nil as PickerOneNumber.ID?)
                    ForEach(numbers) { number in
                        Text(String(format: "%i", number.number)).tag(number.id as PickerOneNumber.ID?)
                    }
                }
            }
            .padding()
            .frame(maxWidth: .infinity)
            .frame(height: 200, alignment: .center)
            .background(.gray)
            
            VStack {
                Text("Selection:")
                Text(selectedNumber?.uuidString ?? "No selection")
            }
            .font(.system(size: 12))
            .padding(10)
            
            Button {
                dismiss()
            } label: {
                Text("Close")
            }
            .padding(.top, 25)
            
            Spacer()
        }
        .transition(.move(edge: .bottom))
        // .animation(.easeInOut, value: isShowing)
        
        .onAppear {
            // self.selectedNumber = numbers.first?.id
        }
    }
}

struct PickerOneNumber: Identifiable {
    let id = UUID()
    
    let number: Int
}

The problem is only the show selected value in the picker. When I run the app the selection is ok and visible.

The error I get is the following:

Picker: the selection "Optional(17973262-4A94-4CC2-83D1-804E46871308)" is invalid and does not have an associated tag, this will give undefined results. Picker: the selection "Optional(17973262-4A94-4CC2-83D1-804E46871308)" is invalid and does not have an associated tag, this will give undefined results. Picker: the selection "Optional(ACCC7A38-8607-4997-89EF-BF9C78E5C167)" is invalid and does not have an associated tag, this will give undefined results.

When I change the selection in the State property it works fine with the picker but the selected value doesn't go back to the calling view.


Solution

  • This doesn't work because every time FilterSheet.init is called, you create three picker options with totally different ids.

    let numbers: [PickerOneNumber] = [
        .init(number: 1),
        .init(number: 2),
        .init(number: 3)
    ]
    

    None of these options will have the same id as the id of the previously-selected number. And that is what the error in the console is telling you.

    You can move the declaration of numbers out of FilterSheet and turn it into a global constant. This way, it is only initialised once, and the ids of the options will not change when you open the picker for the second time.

    You said in the comments that in the real app you are going to use NSManagedObjectIDs as the id, so you won't actually have this problem in your real app as long as you use Core Data correctly. You will fetch the options from Core Data in FilterSheet, and they will have the same NSManagedObjectIDs every time.

    There is also the case where the currently selected option got removed from the database. You might want to check that when deleting objects and set selectedNumber in the view model to nil when the current selection is deleted.