Skip to content

Instantly share code, notes, and snippets.

@HarshilShah
Created December 15, 2023 08:20
Show Gist options
  • Save HarshilShah/da0d03cfa1aa65e9ce1fd72ba800cb2a to your computer and use it in GitHub Desktop.
Save HarshilShah/da0d03cfa1aa65e9ce1fd72ba800cb2a to your computer and use it in GitHub Desktop.
Reimplementing SwiftUI's PickerStyle.menu to be able to use any custom ButtonStyle
import SwiftUI
public struct CustomMenuPicker<Item: Hashable, Content: View>: View {
var label: LocalizedStringKey
var items: [Item]
@Binding var selection: Item
var content: (Item) -> Content
public init(
_ label: LocalizedStringKey,
selection: Binding<Item>,
items: [Item],
@ViewBuilder content: @escaping (Item) -> Content
) {
self.label = label
self.items = items
self._selection = selection
self.content = content
}
public var body: some View {
Menu {
ForEach(items, id: \.self) { item in
Toggle(
isOn: Binding(
get: { selection == item },
set: { isOn, _ in
guard isOn else { return }
selection = item
}
)
) {
content(item)
.tag(item)
}
}
} label: {
HStack(spacing: 5) {
content(selection)
.contentTransition(.opacity)
Image(systemName: "chevron.up.chevron.down")
.imageScale(.small)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment