当 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
,然后将它们的标签设置为 0
、1
、2
(或它们的 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/