1.创建大头针模型类,遵循<MKMapViewDelegate>协议
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface JSAnnotation : NSObject <MKAnnotation>
//经纬度
@property (nonatomic) CLLocationCoordinate2D coordinate;
//标题
@property (nonatomic, copy, nullable) NSString *title;
//子标题
@property (nonatomic, copy, nullable) NSString *subtitle;
@end
2.获取屏幕坐标
3.创建自定义大头针模型对象
4.设置大头针模型信息
5.将自定义大头针添加到MapView中
示例代码:
// 添加大头针到点击的位置
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 获取touch
UITouch *touch = touches.anyObject;
// 获取点击屏幕坐标
CGPoint point = [touch locationInView:touch.view];
// 地图添加大头针模型类,生成模型对象 所有遵守MKAnnotation协议的对象都可以作为大头针的模型
//创建自定义大头针模型对象
JSAnnotation *annotation = [[JSAnnotation alloc]init];
// 设置数据 (mapView可以对iOS坐标和经纬度进行转化)
annotation.coordinate = [self.mapView convertPoint:point toCoordinateFromView:touch.view];
annotation.title = @"自定义大头针";
annotation.subtitle = @"系统样式";
// mapView中添加大头针
[self.mapView addAnnotation:annotation];
}