Skip to content

Instantly share code, notes, and snippets.

@imthath-m
Last active October 4, 2022 08:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imthath-m/469cee5dde579d7892e4233811f7b17c to your computer and use it in GitHub Desktop.
Save imthath-m/469cee5dde579d7892e4233811f7b17c to your computer and use it in GitHub Desktop.
@available (iOS 14.0, *)
public struct MenuPicker<T, V: View>: View {
@Binding var selected: Int
var array: [T]
var title: String?
let mapping: (T) -> V
public init(selected: Binding<Int>, array: [T], title: String? = nil,
mapping: @escaping (T) -> V) {
self._selected = selected
self.array = array
self.title = title
self.mapping = mapping
}
public var body: some View {
if let existingTitle = title {
HStack {
Text(existingTitle)
.foregroundColor(.primary)
.padding(.horizontal)
menu
}
} else {
menu
}
}
var menu: some View {
Menu(content: {
ForEach(array.indices, id: \.self) { index in
Button(action: {
selected = index
}, label: {
view(for: index)
})
}
}, label: {
mapping(array[selected])
})
}
@ViewBuilder func view(for index: Int) -> some View {
if selected == index {
HStack {
Image(systemName: "checkmark")
self.mapping(array[index])
}
} else {
self.mapping(array[index])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment