Skip to content

Instantly share code, notes, and snippets.

@dfrobison
Last active October 9, 2020 02:34
Show Gist options
  • Save dfrobison/4d25599c7e31548a550b905c52c9e5ea to your computer and use it in GitHub Desktop.
Save dfrobison/4d25599c7e31548a550b905c52c9e5ea to your computer and use it in GitHub Desktop.
[iOS 14 Menu Example]
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)
menu
}
} else {
menu
}
}
var menu: some View {
Menu(content: {
Picker(selection: $selected, label: Text("")) {
ForEach(array.indices, id: \.self) { index in
Button(action: {
selected = index
}, label: {
mapping(array[index])
})
}
}
}
, label: {
mapping(array[selected])
Image(systemName: "chevron.down")
.font(.system(size: UIFont.preferredFont(forTextStyle: .footnote).pointSize, weight: .regular))
}
)
}
}
struct MView: View {
let name: String
var body: some View {
Text(name)
}
}
func MapIt(name: String) -> MView
{
MView(name: name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment