Custom pins in Swift for iOS
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
I am using MKMapViewDelegate’s method to customize the pins.
guard !annotation.isKindOfClass(MKUserLocation) is excluding the user location so I still have the standard blue dot for the current location.
We need to create an instance of a pin that later on will be applied to the locations on the map. Lets start with assigning identifier:
let annotationIdentifier = “AnnotationIdentifier”
Then call the dequeuedAnnotationView on it
Then we need to configure the image that is going to be assigned to the pin:
annotationView.canShowCallout = true to display the image. Then you can just assign UIImage to the annotationView.image
But I needed multiple images to be randomly assigned to pins every time the map loads. In order to achieve it I’ve created an array of images and assigned an image from array at random index with the help of arc4random_uniform method:
if let annotationView = annotationView {
// Configure your annotation view here
annotationView.canShowCallout = true
let unicorn = UIImage(named: “unicorn.png”)
let panda = UIImage(named: “redpanda3d.png”)
let arr = [unicorn, panda]
let randomIndex = Int(arc4random_uniform(UInt32(arr.count)))
annotationView.image = arr[randomIndex]
}
Bitcoin tip jar: bc1qgpl6lhf09j6kcdvkh8cz90p4cfxuyfec3ecjrd
Ethereum tip jar: 0x7e0Bf6D50b5F5fcbf76A16Bd5285CE0c74C063a9
Originally published at objectivecmakesyouwanttopicklongnames.wordpress.comon July 25, 2016.