Swift - Add MKAnnotationView To MKMapView

后端 未结 3 644
野的像风
野的像风 2020-11-30 04:13

I\'m trying to add MKAnnotationView to MKMapView but I can\'t do it… Can anyone help me?

Here is my code:

override func vie         


        
3条回答
  •  天涯浪人
    2020-11-30 04:49

    You need to implement the viewForAnnotation delegate method and return an MKAnnotationView from there.

    Here's an example:

    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
    }
    

    Remember you need to create a plain MKAnnotationView when you want to use your own custom image. The MKPinAnnotationView should only be used for the standard pin annotations.

    Also note you should not try to access locationManager.location immediately after calling startUpdatingLocation. It may not be ready yet.

    Use the didUpdateLocations delegate method.

    You also need to call requestAlwaysAuthorization/requestWhenInUseAuthorization (see Location Services not working in iOS 8).

提交回复
热议问题