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

问题描述

@pretep

嗨,

我想在 UserDefaults 中存储地图状态。是否有可能做这样的事情:

@AppStorage("myMapType") var mapType: MKMapType = .standard

或者我必须改为访问 MKMapType 的 rawValue 吗?我怎么能这样做?提前致谢

彼得

解决方法

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
    }
}