【发布时间】:2014-08-19 11:36:29
【问题描述】:
我正在尝试将MKAnnotationView 添加到MKMapView,但我做不到...谁能帮帮我?
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
var latitude:CLLocationDegrees = locationManager.location.coordinate.latitude
var longitude:CLLocationDegrees = locationManager.location.coordinate.longitude
var homeLati: CLLocationDegrees = 40.01540192
var homeLong: CLLocationDegrees = 20.87901079
var latDelta:CLLocationDegrees = 0.01
var longDelta:CLLocationDegrees = 0.01
var theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var myHome:CLLocationCoordinate2D = CLLocationCoordinate2DMake(homeLati, homeLong)
var myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
var theRegion:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, theSpan)
self.theMapView.setRegion(theRegion, animated: true)
self.theMapView.mapType = MKMapType.Hybrid
self.theMapView.showsUserLocation = true
///Red Pin
var myHomePin = MKPointAnnotation()
myHomePin.coordinate = myHome
myHomePin.title = "Home"
myHomePin.subtitle = "Bogdan's home"
self.theMapView.addAnnotation(myHomePin)
var anView:MKAnnotationView = MKAnnotationView()
anView.annotation = myHomePin
anView.image = UIImage(named:"xaxas")
anView.canShowCallout = true
anView.enabled = true
}
【问题讨论】:
-
请参阅stackoverflow.com/questions/24523702/… 以获取使用 MKPinAnnotationView 的示例。您可以轻松地将其更改为普通的 MKAnnotationView 并设置图像。您不需要自定义注释类来满足您的目的(MKPointAnnotation 很好)。
-
另请注意,您不应在调用 startUpdatingLocation 后立即尝试访问 locationManager.location。它可能还没有准备好。使用 didUpdateLocations 委托方法。您还需要调用 requestAlwaysAuthorization/requestWhenInUseAuthorization(请参阅stackoverflow.com/questions/24062509/…)。
-
@Anna 它可以工作,但我无法设置我尝试在 Images.xcassets 中添加的
pinView!.image = UIImage(contentsOfFile: "xaxas")和pinView!.image = UIImage(named: "xaxas")但未成功... -
UIImage(named:"xaxas")应该可以工作,并确保拼写完全正确正确,包括大写/小写。尝试将图像与其他项目文件而不是 Images.xcassets 一起放置。在使用自定义图像时,创建一个普通的 MKAnnotationView 而不是 MKPinAnnotationView 也很重要。
标签: mkmapview swift mkannotation mkannotationview