準備任務:
infoplist 檔案中配置:Localization native development region
viewcontroller .m:
#import "ViewController.h"#import#import "HMAnnotation.h"
#import "HMAnnotationView.h"
#import "HMAnnotation.h"
#import <MapKit/MapKit.h>
//在loadview方法中定義mapview
- (void)loadView {
MKMapView *mapView = [[MKMapView alloc] init];
self.view = mapView;
self.mapView = mapView;
mapView.delegate = self;
}
自定義的大頭針,保證大頭針紮在地圖上
!
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
{
// 獲取當前的觸控物件
UITouch *touch = [touches anyObject];
// 使用者觸控的點
CGPoint location = [touch locationInView:self.view];
// 讓大頭針在底部在觸控點上
UIImage *image = [UIImage imageNamed:@"category_1"];
location.y = location.y - image.size.height * 0.5;
// 把View上座標的點,轉換為地圖經緯度
CLLocationCoordinate2D coordinate = [self.mapView convertPoint:location toCoordinateFromView:self.view];
// 新增大頭針(標註)
HMAnnotation *annotation = [[HMAnnotation alloc] init];
annotation.coordinate = coordinate;
annotation.title = @"黑馬程式設計師";
annotation.subtitle = @"IT教育領導者";
// 設定一個0-4的隨機數
annotation.type = arc4random_uniform(5);
// 新增大頭針模型到地圖上
[self.mapView addAnnotation:annotation];
}
// 返回一個可以重用的大頭針
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation
{
if ([annotation isKindOfClass:[HMAnnotation class]]) {
NSString *reuseID = @"hmAnnotationView";
HMAnnotationView *annotationView = (HMAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseID];
if (annotationView == nil) {
annotationView = [[HMAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseID];
annotationView.canShowCallout = YES;
}
annotationView.annotation = annotation;
return annotationView;
}
return nil;
}
/**
只有當大頭針被新增到了,地圖上之後,才能執行動畫
*/
/**
當大頭針已經被新增到了地圖執行
@param views 大頭針陣列
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray*)views
{
for (MKAnnotationView *annotationView in views) {
// 1. 記錄當前大頭針的位置
CGPoint center = annotationView.center;
// 2. 使用不帶動畫的方式,把大頭針檢視移動地圖的頂部
annotationView.center = CGPointMake(center.x, 0);
// 3. 使用動畫讓大頭針檢視回到原來的位置
[UIView animateWithDuration:0.2 animations:^{
annotationView.center = center;
}];
}
}