简体   繁体   English

无法获取iOS MapKit Annotation来显示标题和副标题

[英]Can't get iOS MapKit Annotation to show title and subtitle

I'm having issues showing a map annotation within xCode. 我在xCode中显示地图注释时遇到问题。 I am able to show a pin on the correct coordinates, however I cannot seem to figure out how to show an annotation with a title and subtitle. 我能够在正确的坐标上显示一个图钉,但我似乎无法弄清楚如何显示带有标题和副标题的注释。

I'm a newbie to xCode and Swift, so apologies if I use incorrect terminology (or if this is a really simple problem to solve!) I've been searching the web for about 2 hours now, trying different variations to my code, but I can't get it working! 我是xCode和Swift的新手,所以如果我使用不正确的术语(或者如果这是一个非常简单的问题要解决的话),我会道歉!)我已经在网上搜索了大约2个小时,尝试了不同的代码变体,但我不能让它运作!

I'm developing a simple app where users can browse locations and then see it pinned on a map. 我正在开发一个简单的应用程序,用户可以浏览位置,然后将其固定在地图上。 Once people click through from a location to the MapViewController, I'm trying to just show a map with the location pinned and an annotation with title and subtitle. 一旦人们从一个位置点击进入MapViewController,我就会尝试显示一个固定位置的地图和一个带标题和副标题的注释。 I've figured everything out except for the title and subtitle, so I'd appreciate any help! 除了标题和副标题外,我已经知道了所有内容,所以我很感激任何帮助!

override func viewDidLoad() {
    super.viewDidLoad()

    // Location pin
    let initialLocation = CLLocation(latitude: location.latitude, longitude: location.longitude)
    self.centerMapOnLocation(location: initialLocation)


    // Annotation
    let annotation = MKPointAnnotation()
    annotation.title = self.location.name
    annotation.subtitle = self.location.type
    annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
    mapView.addAnnotation(location)

}

// Map Center on Location
func centerMapOnLocation(location: CLLocation) {
    let regionRadius: CLLocationDistance = 1000
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
    regionRadius * 2.0, regionRadius * 2.0)
    mapView.setRegion(coordinateRegion, animated: true)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

Make sure your class conforms to the MGLMapViewDelegate and use the following method. 确保您的类符合MGLMapViewDelegate并使用以下方法。

func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
   return true
}

I wonder if you should add annotation instead of location into the mapView, ie: 我想知道你是否应该在mapView中添加annotation而不是location ,即:

mapView.addAnnotation(annotation)

And if you want to show the callout programmatically, you can call like this: 如果你想以编程方式显示标注,你可以像这样调用:

mapView.selectAnnotation(annotation, animated: true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM