4

是否可以在@App Storage 中保存 MKCoordinateRegion 值?我试过这个。但它不起作用。我收到错误“调用初始化程序时没有完全匹配”。

    @AppStorage("region_key") var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
        span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100)
    )
4

1 回答 1

5

存储在其中的类型AppStorage必须符合RawRepresentable. MKCoordinateRegion不做这个开箱即用,但你可以添加一个扩展来增加一致性:

extension MKCoordinateRegion : RawRepresentable {
    struct RepresentableForm : Codable {
        var centerLat : Double
        var centerLong : Double
        var latDelta: Double
        var longDelta : Double
    }
    
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8), let result = try? JSONDecoder().decode(RepresentableForm.self, from: data)
        else {
            return nil
        }
        self = MKCoordinateRegion(
            center: CLLocationCoordinate2D(latitude: result.centerLat, longitude: result.centerLong),
            span: MKCoordinateSpan(latitudeDelta: result.latDelta, longitudeDelta: result.longDelta)
        )
    }
    
    public var rawValue: String {
        do {
            let data = try JSONEncoder().encode(RepresentableForm(centerLat: self.center.latitude, centerLong: self.center.longitude, latDelta: self.span.latitudeDelta, longDelta: self.span.longitudeDelta))
            return String(data: data, encoding: .utf8) ?? ""
        } catch {
            fatalError()
        }
    }
}
于 2021-04-22T14:55:55.123 回答