[英]SwiftUI: Type does not conform to protocol 'UIViewRepresentable' // My Code
I'm developing a new SwiftUI app and I'm trying to figure out how to make this Swift project compatible with SwiftUI. In this example I am developing Map with directions.我正在开发一个新的 SwiftUI 应用程序,我正在尝试弄清楚如何使这个 Swift 项目与 SwiftUI 兼容。在这个例子中,我正在开发带有说明的 Map。
The problem is that I can't make the UIViewRepresentable work.问题是我无法使 UIViewRepresentable 工作。 I get an error:我得到一个错误:
Type 'DirectionsMap' does not conform to protocol 'UIViewRepresentable'类型“DirectionsMap”不符合协议“UIViewRepresentable”
Here is my code:这是我的代码:
import SwiftUI
import MapKit
struct DirectionsMap: UIViewRepresentable {
@EnvironmentObject var model: ViewModel
var business: Businesses
// Start Coordinates for Directions
var start: CLLocationCoordinate2D {
return model.locationManager.location?.coordinate ?? CLLocationCoordinate2D()
}
// End Coordinates for Directions
var end: CLLocationCoordinate2D {
if let lat = business.coordinates?.latitude, let long = business.coordinates?.longitude {
return CLLocationCoordinate2D(latitude: lat, longitude: long)
}
else {
return CLLocationCoordinate2D()
}
}
func makeUIView(context: Context) -> MKMapView {
// Create Map
let map = MKMapView()
map.delegate = context.coordinator
map.showsUserLocation = true
map.userTrackingMode = .followWithHeading
// Create Directions request
var request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: start))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: end))
// Create Directions Object
let directions = MKDirections(request: request)
directions.calculate { response, error in
if error == nil && response != nil {
for route in response!.routes {
map.addOverlay(route.polyline)
map.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100), animated: true)
}
}
}
let annotation = MKPointAnnotation()
annotation.coordinate = end
annotation.title = business.name ?? ""
map.addAnnotation(annotation)
return map
}
func updateUIView(_ uiView: MKMapView, context: Context) {
}
static func dismantleUIView(_ uiView: MKMapView, coordinator: ()) {
uiView.removeAnnotations(uiView.annotations)
uiView.removeOverlays(uiView.overlays)
}
//MARK: - Coordinator
func makeCoordinator() -> Coordinator {
return Coordinator()
}
}
class Coordinator: NSObject, MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = .blue
renderer.lineWidth = 5
return renderer
}
}
Try adding尝试添加
struct DirectionsMap: UIViewRepresentable {
typealias UIViewType = MKMapView // <-- This
Just something I have noticed, when changing the types of the make and update functions the protocol requires explicit typealias.我注意到,当更改 make 和 update 函数的类型时,协议需要显式类型别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.