对你来说
annotation
不是一个
MKPointAnnotation
类型这就是为什么它没有进入
if annotation is MKPointAnnotation {
它应该是这样的:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is pinAnnotation {
let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
pinAnnotationView.pinTintColor = .purple
pinAnnotationView.isDraggable = true
pinAnnotationView.canShowCallout = true
pinAnnotationView.animatesDrop = true
return pinAnnotationView
}
return nil
}
因为
注释
pinAnnotation
类型
我看不见
mapView.delegate = self
在您的代码中。但是,如果你通过故事板分配它,那很好,否则添加它
viewDidLoad
您的完整代码为:
import UIKit
import MapKit
class ViewController: UIViewController,MKMapViewDelegate{
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
let centerLocation = CLLocationCoordinate2D(latitude: 12.964370125970357, longitude: 77.59643554937497)
let mapspan = MKCoordinateSpanMake(0.01, 0.01)
let mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
self.mapView.setRegion(mapregion, animated: true)
let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
mapView.addAnnotation(pin)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is pinAnnotation {
let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
pinAnnotationView.pinTintColor = .purple
pinAnnotationView.isDraggable = true
pinAnnotationView.canShowCallout = true
pinAnnotationView.animatesDrop = true
return pinAnnotationView
}
return nil
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
switch newState {
case .starting:
view.dragState = .dragging
case .ending, .canceling:
view.dragState = .none
default: break
}
}
}
编辑
view.annotation?.coordinate
检查以下代码:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
switch newState {
case .starting:
view.dragState = .dragging
case .ending, .canceling:
//New cordinates
print(view.annotation?.coordinate)
view.dragState = .none
default: break
}
}