启用自定义属性以更改MGLSymbolStyleLayer的图像

时间:2019-03-13 14:59:00

标签: ios objective-c swift mapbox

我有一个要分配给引脚的枚举,因此根据该枚举值,引脚图​​像会有所不同:

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];

,我知道我想基于图钉的type添加各种图像。我唯一能确定的就是我需要将这些图像添加到图层中:

[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属性来设置图钉的图像。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

首先,我们需要一个变量,该变量可用于访问值。为了使其更具可读性,让我们创建一个满足我们需求的变量(例如,在选择销钉时),并立即输入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"];

最后,让我们将图像名称键与先前分配的属性绑定起来:

NSDictionary *typeIcons = @{[MyPointFeature staticTypeKeyWithDynamicType:MyTypeUnknown]: @"img0Key",
                            [MyPointFeature staticTypeKeyWithDynamicType:MyTypeOne]: @"img1Key",
                            [MyPointFeature staticTypeKeyWithDynamicType:MyTypeTwo]: @"img2Key"};
myLayer.iconImageName = [NSExpression expressionWithFormat:@"FUNCTION(%@, 'valueForKeyPath:', myType)", typeIcons];

显然,键名应该用一些常量等包装,但是重构留给读者,这是最简单的解决方案。