首先,我们需要一个变量,它可以用来访问值。为了使其更具可读性,让我们为我们的需要创建一个变量(稍后,例如在选择一个管脚时)和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];