I'm tying to make a picker style that looks like this
Here is the code for the theme
@main
struct GreenPowerPlantUniversalApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.modifier(DarkModeViewModifier())
}
}
class AppThemeViewModel: ObservableObject {
@AppStorage("appThemeSetting") var appThemeSetting = Appearance.system
}
struct DarkModeViewModifier: ViewModifier {
@ObservedObject var appThemeViewModel: AppThemeViewModel = AppThemeViewModel()
public func body(content: Content) -> some View {
content
.preferredColorScheme((appThemeViewModel.appThemeSetting == .system) ? .none : appThemeViewModel.appThemeSetting == .light ? .light : .dark)
}
}
enum Appearance: String, CaseIterable, Identifiable {
case system
case light
case dark
var id: String { self.rawValue }
}
}
struct ThemeSettingsView: View {
@AppStorage("appThemeSetting") var appThemeSetting = GreenPowerPlantUniversalApp.Appearance.system
var body: some View {
VStack {
Picker("Appearance", selection: $appThemeSetting) {
ForEach(GreenPowerPlantUniversalApp.Appearance.allCases) { appearance in
Text(appearance.rawValue.capitalized)
.tag(appearance)
}
}
.pickerStyle(SegmentedPickerStyle())
}.padding(.bottom, 100)
.padding(.horizontal, 20)
}
}
I just don't know where to start to create this as I'm a beginner to swift.
I think it would be best to make a picker style which I don't know how to do but anything to create this would work
CodePudding user response:
While you might be able to implement a custom PickerStyle
, it would be more practical to simply use a custom view in a ForEach
.
First, create a view that you want shown for each item. For example, in the image you provided, each item has an image, a Text
label, and a selector button. So your custom view might look something like this:
struct CustomView: View {
let forAppearance: Appearance
VStack {
//image
//Text label
//Button Selector
}
}
Then, in your body
, you can use your custom view in a ForEach
, thus giving each item a view:
var body: some View {
HStack {
ForEach(GreenPowerPlantUniversalApp.Appearance.allCases) { appearance in
CustomView(forAppearance: appearance)
}
}
Side note: In the code you provided, you used a ForEach
inside of a Picker
. Since ForEach
is usually used to repeat a custom view, and Picker
is used to repeat a default/system view, it's generally a good idea to use either a Picker
or a ForEach
, but not both.