iOS 大头针的基本使用
1.导入头文件
#import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h>
2.为成员变量mapView添加手势识别
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 // 添加手势识别 5 [self.mapView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMapView:)]]; 6 }
3.实现目标方法
1 - (void)tapMapView:(UITapGestureRecognizer *)tap 2 { 3 // 获取所点击view的x,y坐标 4 CGPoint point = [tap locationInView:tap.view]; 5 // x,y坐标转地理坐标 6 CLLocationCoordinate2D coordinate = [self.mapView convertPoint:point toCoordinateFromView:tap.view]; 7 // 初始化大头针,之所以初始化大头针,是因为系统的MKAnnotation各项属性都是只读 8 QKAnnotation *annotation = [[QKAnnotation alloc]init]; 9 // 设置大头针各项属性 10 annotation.title = @"我的大头针"; 11 annotation.subtitle = @"我的大头针--子标题"; 12 annotation.coordinate = coordinate; 13 // 在地图上添加大头针 14 [self.mapView addAnnotation:annotation]; 15 }
3.1系统MKAnnotation各项属性,都是只读的
1 #import <CoreGraphics/CoreGraphics.h> 2 #import <CoreLocation/CoreLocation.h> 3 #import <MapKit/MKFoundation.h> 4 5 @protocol MKAnnotation <NSObject> 6 7 // Center latitude and longitude of the annotion view. 8 // The implementation of this property must be KVO compliant. 9 @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; 10 11 @optional 12 13 // Title and subtitle for use by selection UI. 14 @property (nonatomic, readonly, copy) NSString *title; 15 @property (nonatomic, readonly, copy) NSString *subtitle; 16 17 // Called as a result of dragging an annotation view. 18 - (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate NS_AVAILABLE(10_9, 4_0); 19 20 @end
4.自定义大头针的.h文件,.m文件不需要修改
1 #import <MapKit/MapKit.h> 2 3 @interface QKAnnotation : NSObject<MKAnnotation> 4 5 @property (nonatomic,assign) CLLocationCoordinate2D coordinate; 6 @property (nonatomic, copy) NSString *title; 7 @property (nonatomic, copy) NSString *subtitle; 8 9 @end
#注意:1.MKAnnotation是NSObject, 它是MKAnnotationView的一个属性
2.MKAnnotationView继承自UIView
3.自定义大头针继承自NSObject. 遵守<MKAnnotation>协议,就获得了协议里申明的属性和方法.从3.1的代码可以看出,系统MKAnnotation对象,整个.h文件都是协议,coordinate是必须实现的属性,把readOnly删掉,并为coordinate属性添加assign.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。