2016-03-11 99 views
-3

我正在嘗試創建一個應用程序,您可以在CS:GO中瀏覽完整的武器。Swift在字符串中設置字符串的顏色

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中的標籤中。 所以,這是我的問題。我如何改變uspGrades中字符串的顏色? 例如第一個單元格將顯示Covert,並且應該是紅色的,第二個單元格將顯示Classified並且應該是粉紅色的。

我爲我的壞解釋道歉,但希望有人明白我的意思。

+0

「第一個單元格將顯示Covert,並且應該是紅色的」設置標籤文本的顏色很容易,那麼對你來說最難的部分是什麼? – matt

+0

對不起,如果我解釋錯了。 cell.collectionLabel.text = uspCollections [indexPath.row] 這是將數組加載到標籤中的代碼。我希望標籤根據數組中的字符串更改顏色。所以「隱祕」是紅色的,「分類」是粉紅色等 – Baika

+0

正如你在答案中已經被告知的那樣,你所要做的就是存儲所需的顏色_in_'uspGrades',每種顏色以及它的字符串。然後爲每一行分配字符串作爲標籤的文本和顏色作爲其文本顏色。 – matt

回答

2

你可以讓你的數組作爲touples數組是這樣的:

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

而後就可以存取權限的字符串作爲uspGrades[i].name和顏色uspGrades[i].color

+0

謝謝!這工作完美!不容易成爲編程新手! – Baika

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

謝謝! 嘗試過,但遇到錯誤「在最後兩行使用未解析標識符'uspUpgrades'? – Baika

+0

您需要聲明一個具有相同名稱的實例變量,我已經做了相關編輯。 –