使用MapKit叠加图片和视图教程(2)

来源:互联网 发布:快剪视频软件 编辑:程序博客网 时间:2024/05/22 00:35

如果你喜欢的话那就在地图上放置一个Pin — 注解

如果你用Maps程序搜索过位置信息,那么你肯定看到过在地图上出现的许多Pin。这可以理解为注解(annotation),它是用 MKAnnotationView创建的。你也可以在你的程序中使用注解— 并使用你想要的任何图片,不仅仅是pin!

在程序中使用注解来标出具体的某个景点,这对游客来说非常有用。注解对象的使用方法跟MKOverlay 和MKOverlayView非常类似, 只不过需要使用的类是MKAnnotation 和 MKAnnotationView.

在Annotations群组中创建一个名为 PVAttractionAnnotation 新的类,并继承自 NSObject.

然后用下面的代码替换 PVAttractionAnnotation.h 文件中的内容:

#import <Foundation/Foundation.h>#import <MapKit/MapKit.h> typedef NS_ENUM(NSInteger, PVAttractionType) {    PVAttractionDefault = 0,    PVAttractionRide,    PVAttractionFood,    PVAttractionFirstAid}@interface PVAttractionAnnotation : NSObject  @property (nonatomic) CLLocationCoordinate2D coordinate;@property (nonatomic, strong) NSString *title;@property (nonatomic, strong) NSString *subtitle;@property (nonatomic) PVAttractionType type; @end

上面的代码中,首先是import MapKit,然后为PVAttractionType.定义了一个枚举。这个枚举列出了注解的类型:游乐设施,食物,急救和默认。

接着让这个类遵循 MKAnnotationProtocol. 跟MKOverlay类似, MKAnnotation 有一个required coordinate 属性. 最后是定义了一些属性。

OK, 下面我们来看看PVAttractionAnnotation的实现。

将 PVAttractionAnnotation.m 按照如下修改:

#import “PVAttractionAnnotation.h”

@implementation PVAttractionAnnotation @end

这可能是本文中最简单的实现了!在里面不需要实现任何内容;只需要了解在头文件定义的一些属性即可!

现在需要创建一个MKAnnotation 实例来使用你的注解了。

在Annotation群组中创建另外一个类:PVAttractionAnnotationView 继承自MKAnnotationView.头文件中不需要添加任何内容。

用下面的代码替换PVAttractionAnnotationView.h 中的内容:

#import <Foundation/Foundation.h>#import <MapKit/MapKit.h> @interface PVAttractionAnnotationView : MKAnnotationView @end

将下面的代码添加到 PVAttractionAnnotationView.m:

#import "PVAttractionAnnotationView.h"#import "PVAttractionAnnotation.h" @implementation PVAttractionAnnotationView - (id)initWithAnnotation:(id)annotation reuseIdentifier:(NSString *)reuseIdentifier {    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];    if (self) {        PVAttractionAnnotation *attractionAnnotation = self.annotation;        switch (attractionAnnotation.type) {            case PVAttractionFirstAid:                self.image = [UIImage imageNamed:@"firstaid"];                break;            case PVAttractionFood:                self.image = [UIImage imageNamed:@"food"];                break;            case PVAttractionRide:                self.image = [UIImage imageNamed:@"ride"];                break;            default:                self.image = [UIImage imageNamed:@"star"];                break;        }    }     return self;} @end

上面重载了方法 initWithAnnotation:reuseIdentifier:;根据注解不同的type属性,为注解设置不同的image属性。

非常棒! 现在你创建好了注解和与其相关的view,下面可以将它们添加到map view中了!

首先,你需要准备在 initWithAnnotation:reuseIdentifier:方法中用到的一些资源,以及经典相关的位置信息(MagicMountainAttractions.plist).这些资源包含在 resourcesfor this tutorial – 将它们拷贝到工程的Images群组中。

在plist文件中包含了坐标信息以及其它与公园景点相关的一些详细信息,如下所示:

0 0
原创粉丝点击