我正在尝试在 Swift 中更改 MKMapView 上的图钉图像,但不幸的是它不起作用。知道我做错了什么吗?我在这里看到了一些例子,但没有用。
import UIKit
import MapKit
class AlarmMapViewController: UIViewController {
@IBOutlet weak var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
showAlarms()
map.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func showAlarms(){
map.region.center.latitude = 49
map.region.center.longitude = 12
map.region.span.latitudeDelta = 1
map.region.span.longitudeDelta = 1
for alarm in Alarms.sharedInstance.alarms {
let location = CLLocationCoordinate2D(
latitude: Double(alarm.latitude),
longitude: Double(alarm.longtitude)
)
let annotation = MKPointAnnotation()
annotation.setCoordinate(location)
annotation.title = alarm.name
annotation.subtitle = alarm.description
mapView(map, viewForAnnotation: annotation).annotation = annotation
map.addAnnotation(annotation)
}
}
@IBAction func zoomIn(sender: AnyObject) {
}
@IBAction func changeMapType(sender: AnyObject) {
}
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!.animatesDrop = true
pinView!.image = UIImage(named:"GreenDot")!
}
else {
pinView!.annotation = annotation
}
return pinView
}
}
GreenDot图片可用,并在其他地方使用。
最佳答案
不要忘记设置:
map.delegate = self
并确保您的 UIViewController
实现了 MKMapViewDelegate
协议(protocol)。
如果您忘记这样做,您的 mapView:viewForAnnotation:
实现将不会为您的 map 调用。
此外,pinView!.animatesDrop = true
似乎破坏了自定义图像。您必须将其设置为 false
,或使用 MKAnnotationView
(它没有 animatesDrop
属性)。
参见 this related question如果您想实现自定义放置动画。
关于ios - 在 Swift 中更改 MKMapView 上的图钉图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29116571/