在一个干净的演示项目中,我创建了一个UIViewRepresentable的MapView,它工作得很好。它读取带有多边形的geojson文件并将其绘制在Map上。当我将这段代码复制到我需要此功能的更大的项目中时,我得到了以下错误:
1.类型“MapView”不符合协议“UIViewRepresentable”
1.类型“Context”的值没有成员“coordinator”
我不明白为什么独立的项目编译完美,并集成在我的其他项目,它不。iOS版本设置相同
有人能解释一下什么是错的吗?
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
var coordinate: CLLocationCoordinate2D
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.mapType = .hybrid
map.delegate = context.coordinator
let region = MKCoordinateRegion( center: coordinate, latitudinalMeters: CLLocationDistance(exactly: 5000)!, longitudinalMeters: CLLocationDistance(exactly: 5000)!)
//map.setRegion(map.regionThatFits(region), animated: true)
map.centerCoordinate = coordinate
map.showsCompass = true
map.showsUserLocation = true
map.addOverlays(parseGeoJSON())
return map
}
func updateUIView(_ uiView: MKMapView, context: Context) {
let map = MKMapView()
map.setNeedsDisplay()
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
//MARK: Our delegate handler
final class Coordinator: NSObject, MKMapViewDelegate {
var control: MapView
init(_ control: MapView) {
self.control = control
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer{
if let polygon = overlay as? MKPolygon {
let renderer = MKPolygonRenderer(polygon: overlay as! MKPolygon)
renderer.fillColor = UIColor(red: 57 / 255, green: 255/255, blue: 20/255, alpha: 0.5)
//renderer.fillColor = UIColor(red: 192 / 255, green: 45/255, blue: 233/255, alpha: 0.5)
renderer.strokeColor = UIColor.black
renderer.lineWidth = 2
return renderer
}
return MKOverlayRenderer(overlay: overlay)
}
}
func parseGeoJSON() -> [MKOverlay]{
guard let url = Bundle.main.url(forResource: "zone", withExtension: "json") else {
fatalError("NOT FOUND")
}
var geoJson = [MKGeoJSONObject]()
do{
let data = try Data(contentsOf: url)
geoJson = try MKGeoJSONDecoder().decode(data)
} catch {
}
var overlays = [MKOverlay]()
for item in geoJson{
if let feature = item as? MKGeoJSONFeature {
for geo in feature.geometry{
if let polygon = geo as? MKPolygon{
overlays.append(polygon)
}
}
}
}
return overlays
}
}
struct ContentView: View {
var body: some View {
ZStack(alignment: .top) {
MapView(coordinate: CLLocationCoordinate2D(latitude:34.2226,longitude:-82.4592))
}
.ignoresSafeArea()
.navigationBarHidden(true)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
2条答案
按热度按时间hof1towb1#
它肯定与内置的
MapView
冲突-只是名称不同。原因可能不清楚-只是哪个被编译器在缓存中检测到(在今天的Xcode中这是可怕的)。在我看来,不依赖于命名空间而给予与系统相同的名称是不好的做法--很少有人使用前缀。以防万一flvtvl502#
在我的例子中,我有一个名为“Context”的类,它与Swift UI的Context冲突,我只是将名称更改为“MyContext”,它对我有效。