2017-02-21 59 views
0

我根据标签的名称分配图像。例如,如果标签上写着“汽车”,然后设定的图像是“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 
    } 
    } 

但是我已经尝试了几种不同的方式,它不工作。我读过几个不同的答案,但似乎没有一个干净的方式来做到这一点。感谢您的任何意见!

回答

0
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")}) 
+0

感谢您的答复。我收到错误“条件中的变量绑定需要初始化程序” –

+0

已更新@ orange-oc –