Skip to content

Instantly share code, notes, and snippets.

@magnuskahr
Last active February 27, 2023 21:22
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save magnuskahr/b534d803a550cbe5dc6b65f573d5af2f to your computer and use it in GitHub Desktop.
Save magnuskahr/b534d803a550cbe5dc6b65f573d5af2f 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)
}
}
}
@magnuskahr
Copy link
Author

Hey @apocolipse!
That is also a take on using enum for pickers. If a simple text view is what always is needed, I think it is a great solution, however it misses the view flexibility of my version :-)

Also, the best of both world can be done! See this extension for my version:

extension EnumPicker where V == Text {
    init(selected: Binding<T>, title: String? = nil, display: @escaping (T) -> String) {
        self.init(selected: selected, title: title) {
            Text(display($0))
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment