【发布时间】:2017-10-09 08:09:52
【问题描述】:
我正在开发一个 OSX 应用程序。
我对 MKAnnotation 进行了子类化:
import Foundation
import MapKit
class LocationAnnotation: NSObject, MKAnnotation {
var image: NSImage?
var title: String?
var coordinate: CLLocationCoordinate2D
init(image anImage: NSImage?, title aTitle: String, coordinate aCoordinate: CLLocationCoordinate2D) {
self.image = anImage
self.title = aTitle
self.coordinate = aCoordinate
}
}
在我的 NSViewController 子类中,我添加了一个 MKMapViewDelegate,在 Interface Builder 中我添加了一个 MKMapView 并将其委托设置为 NSViewController。
为了找出问题所在,我在我的 ViewDidLoad 方法中将三个位置添加到一个数组中。我在 ViewDidAppear 中将这些注释添加到我的地图中。当我找出问题所在时,我打算将其移至后台线程。
import Cocoa
import MapKit
class ShowLocationsViewController: NSViewController, MKMapViewDelegate {
@IBOutlet var locationMap: MKMapView!
private var myLocationArray: [LocationAnnotation] = []
private var myRegion: MKCoordinateRegion!
//#MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
myLocationArray = []
myRegion = nil
let locLondon = LocationAnnotation(image: nil, title: "London", coordinate: CLLocationCoordinate2DMake(51.522617, -0.139371))
let locWembley = LocationAnnotation(image: nil, title: "Wembley", coordinate: CLLocationCoordinate2DMake(51.555909, -0.279600))
let locGreenwich = LocationAnnotation(image: nil, title: "Greenwich", coordinate: CLLocationCoordinate2DMake(51.476572, -0.001596))
myLocationArray.append(locLondon)
myLocationArray.append(locWembley)
myLocationArray.append(locGreenwich)
myRegion = MKCoordinateRegion.init(center: locLondon.coordinate, span: MKCoordinateSpanMake(0.20, 0.20)) // 20km span
}
override func viewDidAppear() {
locationMap.addAnnotations(myLocationArray)
locationMap.setRegion(myRegion, animated: true)
}
}
当使用委托的方法viewFor注解时:我在日志中打印出每个注解的标题并列出所有三个注解。在另一个委托的方法 didAdd 中,我在日志中打印出我的地图的注释数量,它打印出三个。但是在我的地图上,没有显示注释。我尝试平移和缩放但没有成功。不过,区域已正确设置和显示。
//#MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
print(locationMap.annotations.count, views.count)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is LocationAnnotation {
let annotationIdentifier = "Location"
var annotationView = locationMap.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) as! MKPinAnnotationView?
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
}
annotationView!.canShowCallout = true
print(annotationView!.annotation!.title ?? "no view")
return annotationView
} else {
print("no annotation")
return nil
}
}
当我在 iOS 应用程序中尝试相同的代码时,一切正常。我认为我的委托没有任何问题,因为方法被正确调用了。
如果您能给我任何帮助,我将不胜感激。
【问题讨论】:
-
如果我创建一个新项目,并复制上面发布的代码,一切正常。所以我的项目肯定有问题,但不知道从哪里开始。我试图清理和重建项目,但没有任何改变。我的 ViewController 是在 storyboard 中设置的
标签: swift macos mkmapview mkannotation mkpinannotationview