Swift在数组中设置字符串的颜色

时间:2016-03-11 19:42:06

标签: ios xcode swift uitableview uicolor

我正在尝试创建一个应用程序,您可以在其中浏览CS:GO中的武器装饰。

    var uspGrades = ["Covert", "Classified", "Classified", "Classified", "Restricted", "Restricted", "Restricted", "Restricted", "Mil-Spec", "Mil-Spec", "Mil-Spec", "Mil-Spec", "Mil-Spec", "Mil-Spec", "Industrial", "Industrial", "Industrial",]

这是具有武器装饰条件的阵列。所有这些现在都显示在TableViewCell的Label中。 所以,这是我的问题。如何更改uspGrades中字符串的颜色? 例如,第一个单元格将显示隐藏,并且应该是红色,第二个单元格将显示分类,应该是粉红色。

我为我的错误解释道歉,但希望有人理解我的意思。

2 个答案:

答案 0 :(得分:2)

你可以把你的数组作为这样的一系列操作:

let uspGrades: [(name: String, color: UIColor)] = [("Covert", UIColor.redColor()), ("Classified", UIColor.blueColor())]

然后您可以将字符串作为uspGrades[i].name访问,并将其颜色设置为uspGrades[i].color

答案 1 :(得分:1)

使用简单的结构来存储字符串和颜色组合。类似的东西:

struct Weapon {

     let name : String
     let color : UIColor

}

//声明你的数据源变量

private var uspGrades : [Weapon]!

然后填充数据源:

func populateDatasource {
    self.uspGrades = [Weapon]()

    self.uspGrades.append(Weapon("Covert", UIColor.redColor())
    self.uspGrades.append(Weapon("Classified", UIColor.pinkColor())
...
...

}

最后,实现UITableView数据源方法,并设置属性,例如:

func tableView(tableView: UITableView, cellForRowAtIndexPath: indexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCellWithIdentifier("cCell")

     cell.textLabel.text = uspGrades[indexPath.row].name
     cell.textLabel.textColor = uspGrades[indexPath.row].color
}