Swift2 iOS9 - 如何在我的代码中获取自定义图像而不是默认注释红色图钉

时间:2016-04-29 12:10:51

标签: ios

这是我的代码。我已经尝试了所有可用的解决方案但是我无法在我的代码中放置我想要的图像而不是默认的注释红色引脚。

SimilarActivityBean

enter image description here

感谢任何帮助。谢谢

1 个答案:

答案 0 :(得分:0)

您想要自定义默认注释?如果是,您可以参考此帖How to create Custom MKAnnotationView and custom annotation title and subtitle

以下是Swift 2中的示例

class MapViewController: UIViewController {


    @IBOutlet weak var mapView: MKMapView!

    let initialLocation = CLLocation(latitude: 34.074094, longitude: -118.396329)
    let regionRadius: CLLocationDistance = 1000

    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
            regionRadius * 2.0, regionRadius * 2.0)
        self.mapView.setRegion(coordinateRegion, animated: true)
    }

    override func viewDidLoad() {
        self.mapView.delegate = self
        self.centerMapOnLocation(initialLocation)

        let location = CLLocationCoordinate2D(latitude: 34.074094, longitude: -118.396329)
        let annotation = CustomAnnotation(coordinate: location, imageName: "pinIcon", title: "Test", subtitle: "Detail", enableInfoButton: false)

        self.mapView.addAnnotation(annotation);
    }
}

extension MapViewController: MKMapViewDelegate {
    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

        if (annotation is MKUserLocation) {
            return nil
        }

        let pinIdentifier = "pinIdentifier"
        var view: MKAnnotationView
        if (annotation.isKindOfClass(CustomAnnotation)) {
            if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(pinIdentifier)
                as MKAnnotationView? {
                    dequeuedView.annotation = annotation
                    view = dequeuedView
            } else {
                view = MKAnnotationView(annotation: annotation, reuseIdentifier: pinIdentifier)
                view.canShowCallout = true

                //Set custome image
                let customAnnotation = annotation as! CustomAnnotation
                view.image = UIImage(named:customAnnotation.imageName!)
            }

            return view
        }

        return nil
    }

}

class CustomAnnotation : NSObject, MKAnnotation {

    var coordinate: CLLocationCoordinate2D
    var imageName: String?
    var title: String?
    var subtitle: String?
    var enableInfoButton : Bool

    init(coordinate: CLLocationCoordinate2D, imageName: String, title: String, subtitle: String, enableInfoButton : Bool) {
        self.coordinate = coordinate
        self.imageName = imageName
        self.title = title
        self.subtitle = subtitle
        self.enableInfoButton = enableInfoButton;
    }
}

这是我在屏幕上显示的自定义图像

enter image description here