Deriving MKAnnotationView and linking it to a NIB file
I need to derive a new class from the MKAnnotationView just like in the WeatherMap project from Apple but with the graphic part defined through a NIB 开发者_Python百科file: is there a way of doing this? Do I have to create a new controller?
One way to do it is to load a view from a nib, then add the view as a subview to your MKAnnotationView. You do not need to create any new controllers.
First, create your MKAnnotationView subclass, with a property into which you'll load the NIB's custom view:
@interface MapAnnotationView : MKAnnotationView
@property (nonatomic, retain) IBOutlet UIView* loadedView;
Then, in the init method for this class, load the nib and add as a subview:
- (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;
}
Finally, create your MyCustomView NIB (as a UIView). Make the file's owner the above MapAnnotationView class, and attach the view to the IBOutlet defined above.
That's about it.
One problem with the Aidan's solution is that it load the view from nib and then add it as a subview of the custom AnnotationView
. This will result in an extra view sitting in the memory for every visible annotation that you created on the map view. If you have only one annotation, then maybe it doesn't matter. But if you have dozens of annotations on the map at the same time, then that solution is a bit waste of memory and GPU rendering resources.
A simpler and more efficient solution is to override the reuseIdentifier
getter method in your custom MapAnnotationView
, like so:
class MapAnnotationView: MKAnnotationView {
override var reuseIdentifier: String? {
get { return "MapAnnotationView" }
}
}
And that is it, the view will get reused properly. No need to do the trick of add view as subview and etc.
精彩评论