Reputation: 3
I have to set custom image for different pins. With my code I'm able to set custom color for each of them but when I try to set custom image instead of colors, it doesn't work.
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(MyAnnotation *)annotation {
static NSString *identifier = @"MyLocation";
if ([annotation isKindOfClass:[MyAnnotation class]]) {
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[self.myMap dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
} else {
annotationView.annotation = annotation;
}
annotationView.enabled = YES;
annotationView.canShowCallout = NO;
NSString *stringType = [NSString stringWithFormat:@"%@", [(MyAnnotation *)annotationView.annotation stringType]];
if ([stringType isEqualToString:@"0"]) {
annotationView.image = [UIImage imageNamed:@"IconUserCerco.png"];
//annotationView.pinColor = MKPinAnnotationColorGreen;
} else if ([stringType isEqualToString:@"1"]) {
annotationView.image = [UIImage imageNamed:@"IconUserDefault.png"];
//annotationView.pinColor = MKPinAnnotationColorPurple;
} else if ([stringType isEqualToString:@"2"]) {
annotationView.image = [UIImage imageNamed:@"PinUniversity.png"];
//annotationView.pinColor = MKPinAnnotationColorRed;
}
return annotationView;
}
return nil;
}
Any help will be much appreciated. Thanks in advance.
Upvotes: 0
Views: 1104
Reputation: 8995
This is what it looks like in iOS 11.x Swift 4, note this won't work if you make the same mistake as me using MKPinAnnotationView. This will make a pin and you won't be able to change the image behind it.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "pin"
var pav:MKAnnotationView?
if (pav == nil)
{
pav = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pav?.isDraggable = true
pav?.canShowCallout = true
pav?.image = UIImage(named: "WIP.png")
pav?.calloutOffset = CGPoint(x: -8, y: 0)
pav?.autoresizesSubviews = true
// pav?.rightCalloutAccessoryView = UIButton(type: .roundedRect)
pav?.leftCalloutAccessoryView = UIButton(type: .contactAdd)
}
else
{
pav?.annotation = annotation;
}
return pav;
}
Upvotes: 0
Reputation: 3956
Instead of MKPinAnnotationView
can you use MKAnnotationView
? You'll have to use following instead of MKPinAnnotationView
MKAnnotationView *annotationView = [self.myMap dequeueReusableAnnotationViewWithIdentifier:identifier];
iOS 9.0 onwards its recommended to use MKAnnotationView
. That should solve your problem.
Upvotes: 4