Swift - setting different images from array to annotation pins

独自空忆成欢 提交于 2019-12-01 13:15:00

First, you need to create your own class that adopts the MKAnnotation protocol for your annotations -

class RestaurantAnnotation : NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var title: String
    var subtitle: String
    var image: UIImage?

    init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }
}

Then, use instances of this class when you add the annotation and set the image -

for var r=0;r<arrayOfRestaurants.count;r++
    {

        var summonRestaurant:NSDictionary = arrayOfRestaurants[r] as NSDictionary
        var nearbyRestaurant = Restaurant(nearbyRestaurants:summonRestaurant)
        var latRestaurant=(nearbyRestaurant.latitude as NSString).doubleValue
        var longRestaurant=(nearbyRestaurant.longitude as NSString).doubleValue
        let locationOfRestaurant = CLLocationCoordinate2D(
            latitude: latRestaurant as CLLocationDegrees, longitude: longRestaurant as CLLocationDegrees)
        var lunchArray: NSArray = nearbyRestaurant.lunch as NSArray

        let title = nearbyRestaurant.name + "  " + nearbyRestaurant.distance +" km"
        var annotation = RestaurantAnnotation(coordinate, title:title, subtitle:"")
        annotation.image = globalImageArray[r]
        map.addAnnotation(annotation)
}

Now, in your view for annotation you can access the image -

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if !(annotation is RestaurantAnnotation) {
        return nil
    }

    let reuseId = "restaurant"
    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    if anView == nil {
        anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        anView.canShowCallout = true
    }
    else {
        anView.annotation = annotation
    }

    let restaurantAnnotation = annotation as RestaurantAnnotation

    if (restaurantAnnotation.image != nil) {
            anView.image = restaurantAnnotation.image!
            anView.image.layer.setCornerRadius(8.0)
            anView.image.layer.clipsToBounds=true
        }
        else {
         // Perhaps set some default image
        }

    return anView
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!