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.

4

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.

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật