我现在的处境是
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
方法,我需要动态改变注解对象的字幕方法的实现。我需要这样做的原因是因为我正在根据经常变化的纬度和经度进行一些计算(我希望将其显示为副标题)......所以当我第一次创建 id 对象时,它不会在那个时候做那个计算是有意义的。
我如何为我的自定义 id 对象动态覆盖字幕方法?有人可以指出我这样做的方向吗?还是我可以采取任何其他方法?
编辑: 更清楚一点......我想在确定该注释对象的标题和副标题应该是什么之前将注释自定义对象添加到 map 。我想等到用户触摸 map 上的注释......当它显示弹出窗口时,这就是我想要计算显示什么作为副标题的地方。这就是为什么我想到动态覆盖自定义 id 对象的字幕方法。
谢谢!
最佳答案
如果您需要在运行时动态更改方法的实现,则可能需要应用 strategy pattern .
有了C block ,我们可以灵活快速地完成。让您的自定义注释将其 subtitle
的实现委托(delegate)给 block 属性的返回值。然后,在您的 map View 的委托(delegate)中,定义根据您的要求计算副标题的 block ,并将它们分配给注释的属性。
委托(delegate)其 subtitle
实现的自定义注释实现的草图:
typedef NSString* (^AnnotationImplementationSubtitleBlock)();
@interface AnnotationImplementation : NSObject <MKAnnotation>
@property (nonatomic, copy) AnnotationImplementationSubtitleBlock *subtitleBlock;
@end
@implementation AnnotationImplementation
- (NSString *)subtitle
{
return self.subtitleBlock();
}
// Rest of MKAnnotation methods
@end
还有创建和分配 block 的 map View 委托(delegate)方法的实现草图:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
AnnotationImplementation *customAnnotation = (AnnotationImplementation *)annotation;
if (/* some condition causing you to do it one way */) {
customAnnotation.subtitleBlock = ^{
//calculate the subtitle some way
return calculatedSubtitle;
}
}
else if (/* some condition causing you to do it another way */) {
customAnnotation.subtitleBlock = ^{
//calculate the subtitle the other way
return calculatedSubtitle;
}
}
... rest of method
}
关于iphone - iOS 动态覆盖 id<MKAnnotation> 子类中的字幕方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15716166/