Ios 打开自定义属性以更改MGLSymbolStyleLayer的图像

Ios 打开自定义属性以更改MGLSymbolStyleLayer的图像,ios,objective-c,swift,mapbox,Ios,Objective C,Swift,Mapbox,我有这样的枚举,我想分配给管脚,因此根据此枚举值,管脚图像不同: typedef NS_ENUM(NSInteger, MyType) { MyTypeUnknown = 0, MyTypeOne, MyTypeTwo, }; 我已经为非集群管脚设置了图层: MGLSymbolStyleLayer *markerLayer = [[MGLSymbolStyleLayer alloc] initWithIdentifier:@"markerLayerId" source:

我有这样的枚举,我想分配给管脚,因此根据此枚举值,管脚图像不同:

typedef NS_ENUM(NSInteger, MyType) {
    MyTypeUnknown = 0,
    MyTypeOne,
    MyTypeTwo,
};
我已经为非集群管脚设置了图层:

MGLSymbolStyleLayer *markerLayer = [[MGLSymbolStyleLayer alloc] initWithIdentifier:@"markerLayerId" source:source];
markerLayer.predicate = [NSPredicate predicateWithFormat:@"cluster != YES"];
[style addLayer: markerLayer];
我知道我想根据pin的
类型添加各种图像。我唯一确定的是,我需要将这些图像添加到图层:

[style setImage:[UIImage imageNamed:@"img0"] forName:@"img0id"];
[style setImage:[UIImage imageNamed:@"img1"] forName:@"img1id"];
[style setImage:[UIImage imageNamed:@"img2"] forName:@"img2id"];
现在我应该设置名称,但我不确定如何:

markerLayer.iconImageName = [NSExpression expressionForConstantValue:@"???"]; // or withFormat..?
我已重写它们的类以添加自定义属性:

@objc class MyPointFeature: MGLPointFeature {
    @objc var type: MyType = .unknown
}

我真的不知道如何打开
type
属性来设置pin的图像。有什么帮助吗?

首先,我们需要一个变量,可以用来访问值。为了使其最具可读性,让我们为我们的需要(稍后,如选择pin时)创建一个变量,并立即创建MapBox需要的条目:

@objc class MyPointFeature: MGLPointFeature {
    @objc var type: MyType = .unknown {
        didSet {
            self.attributes = ["myType": MyPointFeature .staticTypeKey(dynamicType: type)]
        }
    }

    // This is made without dynamic property name to string cast, because
    // the values shouldn't be changed so easily and a developer without
    // suspecting it's a key somewhere could accidentally create a bug
   // PS. if you have swift-only code, you can make it in MyType enum
   @objc static func staticTypeKey(dynamicType: MyType) -> String {
        switch dynamicType {
        case .one:
            return "one"
        case .two:
            return "two"
        default:
            return "unknown"
        }
    }
}
现在我们要将图像名称注册到给定的密钥:

[style setImage:[UIImage imageNamed:@"img0"] forName:@"img0Key"];
[style setImage:[UIImage imageNamed:@"img1"] forName:@"img1Key"];
[style setImage:[UIImage imageNamed:@"img2"] forName:@"img2Key"];
最后,让我们使用分配的Previous属性绑定图像名称键:

NSDictionary *typeIcons = @{[MyPointFeature staticTypeKeyWithDynamicType:MyTypeUnknown]: @"img0Key",
                            [MyPointFeature staticTypeKeyWithDynamicType:MyTypeOne]: @"img1Key",
                            [MyPointFeature staticTypeKeyWithDynamicType:MyTypeTwo]: @"img2Key"};
myLayer.iconImageName = [NSExpression expressionWithFormat:@"FUNCTION(%@, 'valueForKeyPath:', myType)", typeIcons];
显然,键名应该包装在一些常量等中,但重构留给读者,这是最简单的工作解决方案