自定义大头针

{大头针效果图

自定义大头针其实没什么东西,讲讲简单的自定义大头针吧!


自定义大头针
  • 1.需要定义大头针模型(里面至少有三个属性)

    #import <Foundation/Foundation.h>
    #import <MapKit/MapKit.h>
    
     @interface AnnotationModel : NSObject<MKAnnotation>
    
    /*
    
      1.导入框架
    
      2.遵守大头针模型的协议
    
      3.重写3个属性
    
    */
    
    /*
       大头针的位置
    */
    @property(nonatomic,assign) CLLocationCoordinate2D coordinate;
    /*
      大头针的标题
    */
    @property(nonatomic,copy) NSString *title;
    /*
      大头针的子标题
    */
    @property(nonatomic,copy) NSString *subtitle;
    
  • 2.在此我是采取单击mapView的方式来获取大头针的添加(给mapView添加手势),调用手势方法来添加大头针

添加大头针
  • 3.在大头针添加的时候回调用一个方法(在里面进行对大头针的各种设置):里面有很多的细节,需要的就认真研究

     -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
     {
           //判断当前大头针是不是用户位置的数据模型
     if ([annotation isKindOfClass:[MKUserLocation class]])
    {
      //返回nil系统自动处理
      return nil;
    }
    
    //1.从缓存池里面取
    
    //注意:默认情况下 MKAnotationView 是无法显示的,如果想自定义大头针,可以使用MKNotationView的子类MKPinAnnotationView
    
     static NSString *annotationID = @"annotationID";
    
     //判断当前的大头针数据模型是不是用户位置的数据模型
    
     //注意:如果是自定义的大头针,默认情况下大头针是不会显示标题的,需要自己手动显示设置
     MKAnnotationView *annotationView = [self.mapView dequeueReusableAnnotationViewWithIdentifier:annotationID];
    
     //2.如果缓存池中没有,创建一个新的
      if (!annotationView) {
      
      annotationView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:annotationID];
      //设置打头阵的颜色
     // annotationView.pinTintColor = [UIColor purpleColor];
      //设置大头针从天而降
     // annotationView.animatesDrop = YES;
      //设置大头针标题是否显示
      annotationView.canShowCallout = YES;
      //设置大头针显示区域的偏移位
      //annotationView.calloutOffset = CGPointMake(-50, 0);
      //设置大头针左边的辅助视图
      annotationView.leftCalloutAccessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"user"]];
      //设置大头针右边的辅助视图
      annotationView.rightCalloutAccessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"电话"]];
      //设置大头针的拖动
      annotationView.draggable = YES;
      
     }
    
    //设置大头针的图片
    //注意:如果你是使用MKPinAnnotationView创建的自定义大头针,那么设置图片无效,因为系统内部会做一下操作覆盖掉我们自己的设置
    annotationView.image = [UIImage imageNamed:@"airplane"];
    
     //3.给大头针View设置数据
      
     annotationView.annotation = annotation;
    
    //4.返回大头针view
    
     return annotationView;
    
     }
    
  • 4.具体的代码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容