如何在SwiftUI中使用@AppStorage存储枚举类型
@预处理 嗨 我想在UserDefaults中存储映射状态。是否可以这样做:如何在SwiftUI中使用@AppStorage存储枚举类型,swiftui,appstorage,Swiftui,Appstorage,@预处理 嗨 我想在UserDefaults中存储映射状态。是否可以这样做: @AppStorage("myMapType") var mapType: MKMapType = .standard 或者我必须访问MKMapType的原始值吗?我怎么能这样做?提前谢谢 Peter使用原始值OK。我该怎么做? import SwiftUI import MapKit struct MapTypeSwitcherView: View { @AppStorage("
@AppStorage("myMapType") var mapType: MKMapType = .standard
或者我必须访问MKMapType
的原始值吗?我怎么能这样做?提前谢谢
Peter使用原始值OK。我该怎么做?
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
}
}