folks. I am new in ios developmet. Now I am trying to develop a dropdown by using the Picker and my goal is to make it as much as possible generic. How can I pass a generic values to my picker's View properties instead of using the SelectMenuItem struct?
Here is my Picker View Component:
struct SelectMenuItem: Identifiable, Hashable {
var id: UUID
var value: String
}
struct SelectionMenuView: View {
var title: String
var menuItems: [SelectMenuItem]
@Binding var selectedOption: SelectMenuItem
var body: some View {
Picker(title, selection: $selectedOption) {
Text("Placeholder")
.foregroundStyle(.red)
ForEach(menuItems, id: \.self){ menuItem in
Text(menuItem.value)
.foregroundStyle(.red)
}
}
}
}
One way you could do this is updating your example of
SelectMenuItem. On top ofHashableandIdentifiablewe will conform toView:Now, every
SelectMenuItemis also a view because it conforms to theViewprotocol.Since you want a placeholder in your picker, and the picker might start without a selected value, we should make the
selectedOptionoptional. This means it can start as nil (no value). If you are passing this value in from a previous screen, or another area in the app, it would be worth making this aBindingotherwise, having the@Stateon this view isn't bad - it all depends:For the
SelectionMenuView, we use a generic typeMenuItem. This generic type is flexible, but we need to tell Swift that it should be something that can be identified, something that is hashable (can be uniquely represented), and is a view:In the body of
SelectionMenuView, we use aForEachto loop through all the menu items. Each menu item is displayed, and we use tag to make sure each one is uniquely identifiable:Finally, if you are passing this selectedOption from another area in the app, you can set it up like so: