1.創(chuàng)建大頭針模型類,遵循<MKMapViewDelegate>協(xié)議
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface JSAnnotation : NSObject <MKAnnotation>
//經(jīng)緯度
@property (nonatomic) CLLocationCoordinate2D coordinate;
//標題
@property (nonatomic, copy, nullable) NSString *title;
//子標題
@property (nonatomic, copy, nullable) NSString *subtitle;
@end
2.獲取屏幕坐標
3.創(chuàng)建自定義大頭針模型對象
4.設置大頭針模型信息
5.將自定義大頭針添加到MapView中
示例代碼:
// 添加大頭針到點擊的位置
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 獲取touch
UITouch *touch = touches.anyObject;
// 獲取點擊屏幕坐標
CGPoint point = [touch locationInView:touch.view];
// 地圖添加大頭針模型類,生成模型對象 所有遵守MKAnnotation協(xié)議的對象都可以作為大頭針的模型
//創(chuàng)建自定義大頭針模型對象
JSAnnotation *annotation = [[JSAnnotation alloc]init];
// 設置數(shù)據(jù) (mapView可以對iOS坐標和經(jīng)緯度進行轉(zhuǎn)化)
annotation.coordinate = [self.mapView convertPoint:point toCoordinateFromView:touch.view];
annotation.title = @"自定義大頭針";
annotation.subtitle = @"系統(tǒng)樣式";
// mapView中添加大頭針
[self.mapView addAnnotation:annotation];
}