ios-MKMapView上添加大头针

来源:互联网 发布:word for mac迅雷下载 编辑:程序博客网 时间:2024/05/06 19:29

在MKMapView上添加大头针有如下几个步骤

首先我们都知道我们在MapView中获取我们的位置的时候,那个蓝色圆点其实就是一个大头针,有一个对应的大头针模型MKUserLocation

同理我们如果要创建自定义的大头针,也应该有一个模型类,所以这个时候我们需要自己去创建一个大头针模型类

在这个模型类当中,我们需要去让它遵守<MKAnnotation>这个协议,然后在这个协议当中的具体内容如下所示,也就是说我们必须要有的属性就是CLLocationCoordinate2D coordinate,其他是可选。

@protocol MKAnnotation <NSObject>// Center latitude and longitude of the annotation view.// The implementation of this property must be KVO compliant.@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;@optional// Title and subtitle for use by selection UI.@property (nonatomic, readonly, copy, nullable) NSString *title;@property (nonatomic, readonly, copy, nullable) NSString *subtitle;// Called as a result of dragging an annotation view.- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate NS_AVAILABLE(10_9, 4_0);@end

下面是自定义的模型类,我们可以把属性直接从上面拷贝下来,然后删除个readonly就可以了。

#import <Foundation/Foundation.h>#import <MapKit/MapKit.h>@interface Annotation : NSObject<MKAnnotation>//包含经纬度的结构体@property (nonatomic) CLLocationCoordinate2D coordinate;//标题@property (nonatomic, copy, nullable) NSString *title;//子标题@property (nonatomic, copy, nullable) NSString *subtitle;@end
有了这个模型类我们就可以去添加大头针了,我们可以考虑根据用户手指所点击的位置,然后去设置大头针,我们可以这么做

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{            //获取触摸对象    UITouch * touch = [touches anyObject];        //获取手指所点击的那个点    CGPoint point = [touch locationInView:self.mapView];        //self.mapView想要转换,将来自mapView中的点转换成经纬度的点    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:point  toCoordinateFromView:self.mapView];    //创建大头针模型,需要我们自定义大头针的模型类    Annotation * annotation = [Annotation new];        //设置经纬度    annotation.coordinate = coordinate;    //设置标题    annotation.title = @"爱你";    annotation.subtitle = @"哈哈";        //添加大头针模型    [self.mapView addAnnotation:annotation];}
效果如下所示


原创粉丝点击