如何在 SwiftUI 中使用 @AppStorage 存储 EnumType

Pet*_*ass 12 swiftui appstorage

我想将地图状态存储在UserDefaults. 是否可以做这样的事情:

@AppStorage("myMapType") var mapType: MKMapType = .standard
Run Code Online (Sandbox Code Playgroud)

或者我必须访问 rawValue 吗MKMapType?我怎么能这样做呢?

lor*_*sum 11

import SwiftUI
import MapKit
struct MapTypeSwitcherView: View {
    @AppStorage("myMapType") var mapType: Int = 0
    let mapCases: [MKMapType] = [.hybrid,.hybridFlyover, .mutedStandard,.satellite,.satelliteFlyover,.standard]
    var body: some View {
        VStack{
            MapViewUIKit()
            ForEach(mapCases, id: \.self ){ type in
                Button(type.rawValue.description, action: {
                    mapType = Int(type.rawValue)
                })
            }
        }
    }
}
struct MapViewUIKit: UIViewRepresentable {
    @AppStorage("myMapType") var mapType: Int = 0

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.mapType = MKMapType(rawValue: UInt(mapType)) ?? .standard
        return mapView
    }
    
    func updateUIView(_ mapView: MKMapView, context: Context) {
        mapView.mapType = MKMapType(rawValue: UInt(mapType)) ?? .standard
    }
}
Run Code Online (Sandbox Code Playgroud)

如果它是一个自定义枚举,您可以使其符合Codable它会简单得多

enum MyValues: String, Codable, CaseIterable{
    case first
    case second
    case third
}
struct NewListView: View {
    @AppStorage("myEnumType") var enumType: MyValues = .first
    var body: some View {
        VStack{
            Text("Hello World!")
            Text(enumType.rawValue)
            Picker("myEnums", selection: $enumType, content: {
                ForEach(MyValues.allCases, id: \.self, content: { item in
                    Text(item.rawValue).tag(item)
                })
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Art*_*uro 10

您可以通过以下方式存储:

@AppStorage("darkThemeOptionSelection") var darkThemeOptionSelection: DarkThemeOptions = .nord

enum DarkThemeOptions: String, CaseIterable {
    case nord
}
Run Code Online (Sandbox Code Playgroud)