派生MKAnnotationView并将其链接到NIB文件

sta*_*kie 1 mkannotationview ios

我需要从MKAnnotationView派生一个新类,就像在Apple 的WeatherMap项目中一样,但是通过NIB文件定义图形部分:有没有办法做到这一点?我必须创建一个新的控制器吗?

Aid*_*n O 13

一种方法是从笔尖加载视图,然后将视图作为子视图添加到MKAnnotationView.您不需要创建任何新控制器.

首先,创建一个MKAnnotationView子类,其中包含一个属性,您将在其中加载NIB的自定义视图:

@interface MapAnnotationView : MKAnnotationView 

@property (nonatomic, retain) IBOutlet UIView* loadedView;
Run Code Online (Sandbox Code Playgroud)

然后,在此类的init方法中,加载nib并添加为子视图:

- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString*)reuseIdentifier
{
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    if (self != nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil];
        if (loadedView){
            [self addSubview:loadedView];
        }
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

最后,创建MyCustomView NIB(作为UIView).使文件的所有者成为上面的MapAnnotationView类,并将视图附加到上面定义的IBOutlet.

就是这样.