A simple picker to pick a enum.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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: