MapView:UIViewRepresentable 不以获取的列表为中心

问题描述

我尝试创建一个地图,其中填充了从核心数据中获取的列表。获取是完美的,但地图并未以列表位置为中心。 例如,所有列表都位于美国,但我的地图显示的是罗马尼亚(我的位置)。

如何让地图显示获取列表的区域。

import SwiftUI
import UIKit
import MapKit


struct MapView: UIViewRepresentable {
    
    @StateObject var jsonModel = JSONviewmodel()
    @Environment(\.managedobjectContext) var context
    @FetchRequest(entity: Listing.entity(),sortDescriptors:[NSSortDescriptor(keyPath: \Listing.publishdate,ascending: false)])
    
    var results : FetchedResults<Listing>

    func updateUIView(_ uiView: MKMapView,context: UIViewRepresentableContext<MapView>) {
        
        @State var center: CLLocationCoordinate2D?
        @State var zoom: MKCoordinateSpan
        // original
        var allAnnotations: [MapAnnotationPin] = []
        
        for data in results {
            
            let title = data.listingtype
            let subtitle: String = "\(data.saleprice < 1 ? data.rentprice : data.saleprice) EUR"
            
            let coordinate = CLLocationCoordinate2D(latitude: data.latitude,longitude: data.longitude)
            
            allAnnotations.append(MapAnnotationPin(title: title,subtitle: subtitle,coordinate: coordinate))
           
        }
        uiView.annotations.forEach { uiView.removeAnnotation($0) }
        uiView.addAnnotations(allAnnotations)
    }
    
    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
        return MKMapView()
    }
}


class MapAnnotationPin: NSObject,MKAnnotation {
    let title: String?
    let subtitle: String?
    let coordinate: CLLocationCoordinate2D
    
    init(title: String?,subtitle: String?,coordinate: CLLocationCoordinate2D) {
        
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}

解决方法

谢谢盖德!

使其工作的最终代码:

let span = MKCoordinateSpan(latitudeDelta: 2.0,longitudeDelta: 2.0)     
let myFavoriteRegion = MKCoordinateRegion(center: coordinate,span: span)
uiView.setRegion(myFavoriteRegion,animated: true)