Home > Enterprise >  Switch Picker to Buttons when utilizing selection type
Switch Picker to Buttons when utilizing selection type

Time:10-30

So I have the following Picker where I can change the map type in real time, which looks like this:

// Map Type
Picker("Map Type", selection: $appVM.mapType) {
    Text("Standard").tag("standard")
    Text("Image").tag("image")
    Text("Hybrid").tag("hybrid")
}
.pickerStyle(.segmented)

What would be the equivalent instead of having a picker, to utilize a group of buttons using a foreach?

I have this as an attempt:

HStack {
    ForEach($appVM.mapType, id: \.self) { item in
        VStack {
            HStack {
                VStack {
                    Button(action: {
                        print("User has selected \(item) map type.")
                    }, label: {
                        ZStack {
                            Text(item)
                        }
                    }) //: Button
                } //: VStack
            } //: HStack
        }
    } //: ForEach
    .onChange(of: $appVM.mapType) { newValue in
        $appVM.mapType = newValue
        log.info("The new map type is: \(newValue)")
    }
} //: HStack

The above code does not work, so I can't seem to mimic the same functionality that Picker() does. Does anyone know what I might be doing wrong? I am getting the following error:

enter image description here

CodePudding user response:

I am going with the assumption that the map type is an enum. I made the enum conform to String and CaseIterable Protocol and then iterated over it in the ForEach. Also, I would get rid of all the nested stacks, a simlpe HStack should do the job. Here's the code:

     HStack {
        ForEach(ViewModel.MapType.allCases, id: \.self) { item in
            VStack {
                HStack {
                    VStack {
                        Button(action: {
                            print("User has selected \(item) map type.")
                            $appVM.mapType.wrappedValue = item
                        }, label: {
                            Text(item.rawValue)
                                .foregroundColor(appVM.mapType == item ? .red : .blue)
                            
                        }) //: Button
                    } //: VStack
                } //: HStack
            }
        } //: ForEach

    } //: HStack
  • Related