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

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

我知道我想根据引脚的类型添加各种图像。我唯一确定的是我需要将这些图像添加到图层中:

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

最佳答案

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

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

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

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

关于ios - 打开自定义属性以更改 MGLSymbolStyleLayer 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144970/

相关文章:

iphone - 尝试构建存档时尝试获取 Apple Mach-O 链接器错误

ios - 将 Youtube 视频以高清格式嵌入 iOS 应用程序

ios - Objective-C(将单个图像上传到服务器)

ios - 我如何将此数据从 BLE 设备转换为结构模型

iphone - MKMapView 到 UIImage iOS 7

swift - Firestore 查询 geohash 过滤

ios - 将数据从 AWS DynamoDB 表加载到 iOS 上的 UITableView

ios - iOS中的自动布局向后兼容性

ios - 需要帮助设置 IF 语句 iOS Swift

iOS swift ImagePickerController : Improving Edit Mode