3

@pretep

你好,

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

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

或者我是否必须访问 rawValue MKMapType?我怎么能这样做?提前致谢

彼得

4

1 回答 1

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

如果它是一个自定义枚举,您可以使其符合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)
                })
            })
        }
    }
}
于 2021-02-28T14:41:04.710 回答