iOS 圖釘的基本使用

來源:互聯網
上載者:User

標籤:style   blog   ar   io   color   os   使用   sp   for   

1.匯入標頭檔

#import <MapKit/MapKit.h>#import <CoreLocation/CoreLocation.h>

2.為成員變數mapView添加手勢識別

1 - (void)viewDidLoad2 {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 @optional12 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.

iOS 圖釘的基本使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.