我是一名新手iOS开发者,需要在iOS地图中实现一个可拖动的注释。我的代码如下所示。无论我做什么,都无法得到一个可拖动的注释。有人能帮忙解决吗?之后,我需要获取指针位置的地址。
RegistrationViewController.swift
class RegistrationViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,MKMapViewDelegate{
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
var centerLocation = CLLocationCoordinate2DMake(12.964370125970357, 77.59643554937497)
var mapspan = MKCoordinateSpanMake(0.01, 0.01)
var mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
self.mapView.setRegion(mapregion, animated: true)
let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
mapView.addAnnotation(pin)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKPointAnnotation {
let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
pinAnnotationView.pinColor = .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
}
}
pinAnnotation.swift
import MapKit
class pinAnnotation:NSObject,MKAnnotation {
var title:String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
init(title:String,subtitle:String,coordinate:CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
}
}
view.dragState = .dragging
在我的情况下有助于更新自定义标记位置,谢谢! - Dhaval H. Nena