gpt4 book ai didi

mkmapview - Swift - 添加 MKAnnotationView 到 MKMapView

转载 作者:IT王子 更新时间:2023-10-29 05:08:26 27 4
gpt4 key购买 nike

我正在尝试将 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
}

最佳答案

您需要实现 viewForAnnotation 委托(delegate)方法并从那里返回一个 MKAnnotationView

这是一个例子:

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if (annotation is MKUserLocation) {
//if annotation is not an MKPointAnnotation (eg. MKUserLocation),
//return nil so map draws default view for it (eg. blue dot)...
return nil
}

let reuseId = "test"

var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.image = UIImage(named:"xaxas")
anView.canShowCallout = true
}
else {
//we are re-using a view, update its annotation reference...
anView.annotation = annotation
}

return anView
}

请记住,当您想要使用自己的自定义图像时,您需要创建一个plain MKAnnotationViewMKPinAnnotationView 应仅用于标准引脚注释。

另请注意,您不应在调用 startUpdatingLocation 后立即尝试访问 locationManager.location。它可能还没有准备好。

使用 didUpdateLocations 委托(delegate)方法。

您还需要调用 requestAlwaysAuthorization/requestWhenInUseAuthorization(参见 Location Services not working in iOS 8)。

关于mkmapview - Swift - 添加 MKAnnotationView 到 MKMapView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24467408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com