標準にクロスヘアを追加したい場合はMKPinAnnotationView
、それをサブクラス化し、クロスヘアを の実装に追加する必要がありますsetDragState:animated:
。
したがって、サブクラス化するには、新しいクラスを作成しますPinWithCrosshairAnnotationView
。.h public インターフェイスはあまり必要としません:
@interface PinWithCrosshairAnnotationView : MKPinAnnotationView
@end
.m 実装setDragState:animated:
は、十字線を追加する a を実装し、実装を呼び出してsuper
、ピンを引っ張ったり落としたりする機能を取得するだけです。フラグがオンの場合もアニメーション化してanimated
いますが、そうする必要はありません。あなたのframe
座標は間違いなく私のものとは異なりますが、上記のコード サンプルから、十字線画像の正しい値を既に把握していることがわかります。
#import "PinWithCrosshairAnnotationView.h"
@interface PinWithCrosshairAnnotationView ()
@property (nonatomic, weak) UIImageView *crosshairImageView;
@end
@implementation PinWithCrosshairAnnotationView
- (void)setDragState:(MKAnnotationViewDragState)newDragState animated:(BOOL)animated
{
if (newDragState == MKAnnotationViewDragStateStarting)
{
// create the crosshair imageview and add it as a subview
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(-1.5, 30, 17.5, 17.5)];
imageView.image = [UIImage imageNamed:@"Crosshairs.png"];
[self addSubview:imageView];
// if the animated flag is on, we'll fade it to visible state
if (animated)
{
imageView.alpha = 0.0;
[UIView animateWithDuration:0.2
animations:^{
imageView.alpha = 1.0;
}];
}
// save a reference to that imageview in a class property
self.crosshairImageView = imageView;
}
else if (newDragState == MKAnnotationViewDragStateEnding || newDragState == MKAnnotationViewDragStateCanceling)
{
if (animated)
{
// if we're animating, let's quickly fade it to invisible
// and in the completion block, we'll remove it
[UIView animateWithDuration:0.2
animations:^{
self.crosshairImageView.alpha = 0.0;
}
completion:^(BOOL finished) {
[self.crosshairImageView removeFromSuperview];
self.crosshairImageView = nil;
}];
}
else
{
// if we're not animating, just remove it
[self.crosshairImageView removeFromSuperview];
self.crosshairImageView = nil;
}
}
// remember to call super so we get all the other wonderful superclass behavior
[super setDragState:newDragState animated:animated];
}
@end
そして明らかに、それに応じてデリゲートの をカスタマイズviewForAnnotation
します。MKMapView
これは最小限のバージョンですが、必要に応じて (コールアウト、タイトル、サブタイトルなど) を調整することは明らかです。
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKAnnotationView *view = [[PinWithCrosshairAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:@"pinwithcrosshairannotation"];
view.draggable = YES;
view.canShowCallout = NO;
return view;
}