MKAnnotationView学习

当我们点击MKAnnotationView进入源码的时候,我们可以看到在#if TARGET_OS_IPHONE在iphone上面是继承的UIView,这样我们就看Iphone上面的属性。annotation,image,centerOffset,canShowCallout,leftCalloutAccessoryView,rightCalloutAccessoryView等属性。下面我自定义一个大头针的标注对象,把上面的属性都显示出来看哈。这些属性到底是什么。下面是官方的自定义大头针

@interfaceSFAnnotation :NSObject

@property(nonatomic,readwrite)CLLocationCoordinate2Dcoordinate;

+ (MKAnnotationView*)createViewAnnotationForMapView:(MKMapView*)mapView annotation:(id)annotation;

@end

实现

@implementationSFAnnotation

- (NSString*)title

{

return@"这个是标题";

}

// optional

- (NSString*)subtitle

{

return@"这个是子标题";

}

+ (MKAnnotationView*)createViewAnnotationForMapView:(MKMapView*)mapView annotation:(id)annotation

{

MKAnnotationView*returnedAnnotationView =

[mapViewdequeueReusableAnnotationViewWithIdentifier:NSStringFromClass([SFAnnotationclass])];

if(returnedAnnotationView ==nil)

{

returnedAnnotationView =

[[MKAnnotationViewalloc]initWithAnnotation:annotation

reuseIdentifier:NSStringFromClass([SFAnnotationclass])];

returnedAnnotationView.canShowCallout=YES;//这个是标注附件是否显示。这必须要是YES。不然点击标注没有任何效果

returnedAnnotationView.centerOffset=CGPointMake( returnedAnnotationView.centerOffset.x+ returnedAnnotationView.image.size.width/2, returnedAnnotationView.centerOffset.y- returnedAnnotationView.image.size.height/2);

}

else

{

returnedAnnotationView.annotation= annotation;

}

returnreturnedAnnotationView;

}

@end

在UIViewController中的代码

- (void)viewDidLoad {

[superviewDidLoad];

_mapView=[[MKMapViewalloc]initWithFrame:CGRectMake(0,0,320,400)];

_mapView.delegate=self;

[self.viewaddSubview:_mapView];

SFAnnotation*annation=[[SFAnnotationalloc]init];

[annationsetCoordinate:CLLocationCoordinate2DMake(30.23423,104.345354)];

[_mapViewaddAnnotation:annation];

SFAnnotation*annation2=[[SFAnnotationalloc]init];

[annation2setCoordinate:CLLocationCoordinate2DMake(30.63423,104.645354)];

[_mapViewaddAnnotation:annation2];

[_mapViewshowAnnotations:@[annation,annation2]animated:YES];

}

- (nullableMKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id)annotation{

MKAnnotationView*returnAnnotationView=nil;

if([annotationisKindOfClass:[SFAnnotationclass]])

{

returnAnnotationView = [SFAnnotationcreateViewAnnotationForMapView:self.mapViewannotation:annotation];

returnAnnotationView.image= [UIImageimageNamed:@"flag.png"];//这是标注显示图片

UIImageView*sfIconView = [[UIImageViewalloc]initWithImage:[UIImageimageNamed:@"SFIcon"]];

returnAnnotationView.leftCalloutAccessoryView= sfIconView;//左标注附件视图

UIButton*rightButton = [UIButtonbuttonWithType:UIButtonTypeDetailDisclosure];

[rightButtonaddTarget:selfaction:@selector(buttonAction)forControlEvents:UIControlEventTouchUpInside];

returnAnnotationView.rightCalloutAccessoryView= rightButton;//右标注附件视图

}

returnreturnAnnotationView;

}

-(void)buttonAction{

NSLog(@"右标注附件视图被点击");

}

效果图如下


MKAnnotationView学习_第1张图片

你可能感兴趣的:(MKAnnotationView学习)