swift - 从匹配的关联值中获取枚举

标签 swift

当 UIImage 与 UIImage 匹配时,如何选择关联值的枚举?

enum ClothingType: String {
    case head
    case body
    case pants

    var imageForClothingType: UIImage {
        switch self {
        case .head: return #imageLiteral(resourceName: "hatsicon")
        case .body: return #imageLiteral(resourceName: "bodyicon")
        case .pants: return #imageLiteral(resourceName: "pantsicon")
        }
    }
}

我想从按下的按钮中选择相应的 ClothingType:

@IBAction func chooseClothingType (_ sender: UIButton) {

    let theImage: UIImage = sender.currentImage!
    let matchingType: ClothingType = theImage
    confirmClothingType(type: matchingType)
}

func confirmClothingType (type: ClothingType) {
    // perform needed function
}

最佳答案

这样做违反了 MVC 的理念和使用枚举的要点。你应该使用枚举,它是一个更简单的数据对象,用于所有底层操作,并且只在显示时渲染图像,并且永远不要读回图像,因为你应该已经知道代表图像的底层枚举值。

我会为 UIButton 设置 tag 属性并使枚举继承 Int。假设您有 3 个 UIButton,然后将它们的标签设置为 012(或它们的 clothingType.rawValue 编程)分别。然后,您可以使用以下实现检索枚举:

enum ClothingType: Int {
    case head = 0
    case body = 1
    case pants = 2

    var imageForClothingType: UIImage {
        switch self {
        case .head: return #imageLiteral(resourceName: "hatsicon")
        case .body: return #imageLiteral(resourceName: "bodyicon")
        case .pants: return #imageLiteral(resourceName: "pantsicon")
        }
    }
}

@IBAction func chooseClothingType (_ sender: UIButton) {

    if let matchingType: ClothingType = ClothingType(rawValue: sender.tag)
    {
        confirmClothingType(type: matchingType)
    }
}

关于swift - 从匹配的关联值中获取枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53404587/

相关文章:

android - 知道我的开发人员是否使用了正确的 "Ad unit ID"

ios - 从后台删除应用程序时,UNUserNotificationCenterDelegate 不工作

swift - "If"语句不适用于可选值

arrays - Swift 如何使用带有索引 [i] 的 for 循环读取数组的所有索引

ios - UITableView 在插入新行时更改位置

macos - 使用数组填充 NSTableView - 绑定(bind)表

ios - 使用 Swift 设置游戏中心?

ios - 声明计算变量后,编译器开始提示类没有初始化器

swift - 使用 Swift/lldb 比较 Intel 和 Arm 寄存器

json - Swift 如何从 JSON 中提取 "sort"字典以在时间序列中绘制它?