【问题标题】:How to store EnumTypes with @AppStorage in SwiftUI如何在 SwiftUI 中使用 @AppStorage 存储 EnumTypes
【发布时间】:2022-05-18 10:53:18
【问题描述】:

@pretep

嗨,

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

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

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

彼得

【问题讨论】:

  • 使用 rawValue
  • 好的。我该怎么做?

标签: swiftui appstorage


【解决方案1】:
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)
                })
            })
        }
    }
}

【讨论】:

    【解决方案2】:

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

    @AppStorage("darkThemeOptionSelection") var darkThemeOptionSelection: DarkThemeOptions = .nord
    
    enum DarkThemeOptions: String, CaseIterable {
        case nord
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-23
      • 2020-11-19
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多