当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
}
答案 0 :(得分:2)
这样做会违反MVC的原理以及使用枚举的意义。您应该对所有基础操作使用枚举,它是一个简单得多的数据对象,并且仅在显示时渲染图像,并且永远不要读回图像,因为您应该已经代表图像知道了其基础枚举值。
我将为tag
设置UIButton
属性,并使枚举继承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)
}
}
答案 1 :(得分:0)
我将继承UIButton
并创建一个属性来设置ClothingType
。
class ClothingButton: UIButton {
var type: ClothingType? {
didSet {
setImage(type?.imageForClothingType, for: .normal)
}
}
}
class ClothingViewController: UIViewController {
@IBAction func chooseClothingType (_ sender: ClothingButton) {
print(sender.type.debugDescription)
}
}