使用数组存储的颜色(字符串)设置标签元素的UIColor

时间:2019-04-01 15:28:42

标签: swift uicolor

我正在开发一个iOS应用(目前只是一个个人项目),并且我试图根据存储在数组中的变量来更改标签bg和文本颜色,我真的很努力!

我尝试过使用几种方法,但是我对Swift还是很陌生,并且不了解最佳实践背后的所有逻辑。

这是我的数组:

data: { COMP_011234567 NYWC-LLUVULylrqhqq5QkMTU: { accountId: "1234567 " accountKey: "COMP_011234567 " accountName: "Test123 " adjusterClaimType: "WC" adjusterKey: "COMP_01WC-LLUVULylrqhqq5QkMTU" assignmentRulesKey: "COMP_011234567 NYWC" companyAdjusterId: 1111111 companyId: "COMP_01" exception: false handlerId: "-LLUVULylrqhqq5QkMTU" key: "COMP_011234567 NYWC-LLUVULylrqhqq5QkMTU" lineOfBusiness: "WC" name: "WC Med Only Direct Without skills - All states" selectedState: "NY" tpa: "no" tpaCompany: "" } } I need to trim() accountId and handlerId. // Already tried this apporach: data.forEach(i => { i.accountId = i.accountId.trim(); i.handlerId = i.handlerId.trim(); })

基本上我认为我可以做这样的事情:

let testItem = [["Name Here"], ["red: 1.0, green: 0, blue: 0, alpha: 1"], ["red: 1.0, green: 0, blue: 0, alpha: 1"]]

但是,那当然行不通...所以有什么主意吗?

1 个答案:

答案 0 :(得分:0)

您可以通过多种方法来执行此操作,以下是一些可以帮助您了解数据收集的方法(还有其他方法)。

您可以简单地创建一组颜色[UIColor]

let colors = [UIColor.red, UIColor.green, UIColor.blue]

labelOne.backgroundColor = colors[0]
labelOne.textColor = colors[2]

您可以将一个标签的所有样式存储在字典[String : UIColor]中:

let labelOneStyling = ["background": UIColor.red, "text": UIColor.blue]

labelOne.backgroundColor = labelOneStyling["background"]
labelOne.textColor = labelOneStyling["text"]

您可以将所有标签样式存储在字典[String : [String : UIColor]]的字典中:

let allLabelStyling = ["labelOne": ["background": UIColor.red, "text": UIColor.blue], "labelTwo": ["background": UIColor.green, "text": UIColor.yellow]]

labelOne.backgroundColor = allLabelStyling["labelOne"]?["background"]
labelOne.textColor = allLabelStyling["labelOne"]?["text"]

一个非常有用的技巧是选择单击任何属性,例如第一个示例中的colors数组,然后选择“显示快速帮助”。 Xcode会告诉您该属性是什么类型。您将看到let colors: [UIColor],它告诉您颜色是UIColors类型数组的常量。 Swift是一种强类型语言,类型是OOP的基础,因此,如果有什么要马上学习的东西,类型就是它。