我正在分配基于标签名称的图像。例如,如果标签上说"汽车",则分配的图像是" Carimage",我将其与此代码一起使用:
if cell.nameLabel.text == “Car” {
if let image = UIImage(named: “CarImage”)
{ cell.imageView?.image = image
}
}
我希望能够为同一图像设置标签的许多变体。我正在用一个数组尝试:
if cell.nameLabel.text == [“Car”, “Automobile”, “Auto”, "Vehicle",] {
if let image = UIImage(named: “Car”)
{ cell.imageView?.image = image
}
}
但是,我以几种不同的方式尝试了这一点,但它无法正常工作。我读过几个不同的答案,但似乎没有一个干净的方法可以做到这一点。谢谢您的任何输入!
let array = ["Car", "Automobile", "Auto", "Vehicle"]
if array.contains(where: {cell.nameLabel.text != nil && $0 == cell.nameLabel.text!}) {
cell.imageView.image = UIImage(named: "CarImage")
}
array.contains(where: {cell.nameLabel.text != nil && $0 == cell.nameLabel.text!})
将检查["Car", "Automobile", "Auto", "Vehicle"]
数组中的任何字符串是否在cell.nameLabel.text
中具有字符串。如果是这样,请在单元格上设置图像。
您可能会很想做这样的事情:
cell.imageView.image = array
.first(where: {cell.nameLabel.text != nil && $0 == cell.nameLabel.text!})
.flatMap({_ in UIImage(named: "CarImage")})