Reputation: 552
I am making a Menu where the selected item has a checkmark. Right now, the checkmark is on the right side::
Button(action: {
self.categoryIndex = index
self.selectedCategory = category
}, label: {
Text(category)
if selectedCategory == categories[index] {
Image(systemName: "checkmark")
}
})
I need the checkmark on the left side, like this picture:
How do I achieve the selections like the photo?
Upvotes: 2
Views: 816
Reputation: 35626
There are probably more ways to do this, but here are two options:
Using a Picker
Picker("Menu", selection: $selection) {
ForEach(1..<5, id: \.self) { number in
Text("Option \(number)")
}
}
.pickerStyle(MenuPickerStyle())
which will be displayed like this (iOS / MacOS):
Using Toggles
This is slightly more involving since you want to bind some kind of action on selections (assuming that you need a single selection, like above), so I don't know if it's worth the trouble, but for pedagogical reasons, here it is:
struct CheckedMenu: View {
@State private var selection = "1"
var body: some View {
Menu("Menu") {
Toggle("Option 1", isOn: bindingForOption("1"))
Toggle("Option 2", isOn: bindingForOption("2"))
}
}
private func bindingForOption(_ option: String) -> Binding<Bool> {
Binding<Bool>(get: { selection == option }, set: { if $0 { selection = option } })
}
}
which will be displayed like this (iOS / MacOS):
Finally, for what is worth, note that the second option (toggles) allows for multiple (unrelated) items to be simultaneously checked, which would be a better choice for "option" menus like:
Upvotes: 4