多年来,我一直试图在地图视图上放置可拖动的注释。(我使用的是默认图钉,而不是我自己的图钉)到目前为止,我只能在设定的坐标处显示它(真的不是什么成就),我需要首先获取注释才能对被选中做出反应,它没有永远不会被didChangeDragState
func 接收。然后我需要能够拖动它,将其放置在新位置并获取新位置的坐标。
我对 Swift 相当陌生,但我承担了一个相当困难的项目。我已经查看了几乎所有可以在谷歌上找到的“ MKAnnotation
Swift 中的可拖动 mapkit”和类似变体。(编辑:我没有找到任何可以阐明我的问题的答案,所有其他答案都给出了如何上传个性化MKAnnotation
的答案。他们都有标题字段,但没有一个答案提到标题字段是必要的,这结果是主要问题。他们只提到我应该设置dragState来控制引脚的移动,但在我的情况下这结果是不正确的,如下所示)无论如何 !下面是我尝试实现 mapView 并添加注释的代码。
var currentLat:CLLocationDegrees!
var currentLong:CLLocationDegrees!
var currentCoordinate:CLLocationCoordinate2D!
....
override func viewDidAppear(animated: Bool) {
let annotation = PinAnnotationClass()
annotation.setCoordinate(currentCoordinate)
//annotation.setCoordinate(currentCoordinate)
//AnnotationView()
self.mapView.addAnnotation(annotation)
}
override func viewDidLoad() {
super.viewDidLoad()
println("hello!")
self.mapView.delegate = self
loadMap()
findPath()
}
func loadMap()
{
currentCoordinate = CLLocationCoordinate2DMake(currentLat, currentLong)
var mapSpan = MKCoordinateSpanMake(0.01, 0.01)
var mapRegion = MKCoordinateRegionMake(currentCoordinate, mapSpan)
self.mapView.setRegion(mapRegion, animated: true)
}
随着扩展:
extension DetailsViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.draggable = true
pinView!.annotation.coordinate
pinView!.animatesDrop = true
pinView!.pinColor = .Green
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
if (newState == MKAnnotationViewDragState.Starting) {
view.dragState = MKAnnotationViewDragState.Dragging
} else if (newState == MKAnnotationViewDragState.Ending || newState == MKAnnotationViewDragState.Canceling){
view.dragState = MKAnnotationViewDragState.None
}
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
if let annotation = view.annotation as? PinAnnotationClass{
}
}
我还有一个自定义 PinAnnotation 类:
import Foundation
import MapKit
class PinAnnotationClass : NSObject, MKAnnotation {
private var coord: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
var coordinate: CLLocationCoordinate2D {
get {
return coord
}
}
var title: String = ""
var subtitle: String = ""
func setCoordinate(newCoordinate: CLLocationCoordinate2D) {
self.coord = newCoordinate
}