准备任务:
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;
}];
}
}
网友评论