com*_*rik 5 mkcoordinateregion swiftui appstorage
是否可以在 @App Storage 中保存 MKCooperativeRegion 值?我试过这个。但这不起作用。我收到错误“调用初始化程序时没有完全匹配”。
@AppStorage("region_key") var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100)
)
Run Code Online (Sandbox Code Playgroud)
存储的类型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()
}
}
}
Run Code Online (Sandbox Code Playgroud)