Skip to content

Instantly share code, notes, and snippets.

@wb-towa
Forked from magnuskahr/EnumPicker.swift
Created July 18, 2020 13:31
Show Gist options
  • Save wb-towa/54d05f0856dd7c6ed8320b3a9549be82 to your computer and use it in GitHub Desktop.
Save wb-towa/54d05f0856dd7c6ed8320b3a9549be82 to your computer and use it in GitHub Desktop.
A simple picker to pick a enum.
import SwiftUI
struct EnumPicker<T: Hashable & CaseIterable, V: View>: View {
@Binding var selected: T
var title: String? = nil
let mapping: (T) -> V
var body: some View {
Picker(selection: $selected, label: Text(title ?? "")) {
ForEach(Array(T.allCases), id: \.self) {
mapping($0).tag($0)
}
}
}
}
extension EnumPicker where T: RawRepresentable, T.RawValue == String, V == Text {
init(selected: Binding<T>, title: String? = nil) {
self.init(selected: selected, title: title) {
Text($0.rawValue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment