如果你想在标准中添加一个十字准线MKPinAnnotationView
,你应该继承它,然后在你的实现中添加你的十字准线setDragState:animated:
。
因此,要子类化,请创建一个新类,例如PinWithCrosshairAnnotationView
. .h 公共接口不需要太多:
@interface PinWithCrosshairAnnotationView : MKPinAnnotationView
@end
.m 实现只是实现了一个setDragState:animated:
添加你的十字准线的实现,然后调用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;
}