iphone - iOS 动态覆盖 id<MKAnnotation> 子类中的字幕方法

标签 iphone ios overriding mapkit subclass

我现在的处境是

- (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/

相关文章:

ios - 应用因 Facebook SDK 和 Flurry SDK 中的 advertisingIdentifier 而被拒绝

ios - 加载更多到 UITableView 中的最后一个位置

ios - Flutter_tts 无法在 iOS 上运行

c# - 如何覆盖非虚方法?

php - 在用 PHP 创建的 iPhone 上解析 XML

ios - 如何在给定不同排序参数的情况下自动重绘 UITableViewCells

iphone - NSLog InterfaceRotation 在模拟器上不起作用?

C# native IOS 与 .NET

api - Odoo 新 API - 覆盖旧 API 函数字段

python - Marshmallow:如何覆盖此 Python 类的构造函数?