我有一个网格UICollectionView
,在每个单元格中显示一个文本标签。尽管该图显示了每个单元格中的不同属性,但我无法弄清楚如何在NSAttributedString.Key.foregroundColor
上存储和访问特定的indexPath.item
值。
对于文本,我有一个字符串值数组,可以通过cellForItemAt indexPath中的indexPath.item调用它。但是我不知道如何创建等效的属性值数组。
型号: 让myText = [“ Pos.1”,“ Main Verb”,“ Pos.2” ....等等
Collection View数据源:
func colletionView(_ collectionView.UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCell", for: indexPath as! CVCell
let text = myModel.myText[indexPath.item]
let myAttribute = [NSAttributedString.Key.foregroundColor: UIColor.blue]
let myAttributedText = NSAttributedString(string: text, attributes: myAttributes as [NSAttributedString.Key : Any])
cell.label.attributedText = myAttributedText
return cell
}
我尝试创建NSAttributedString或NSAttribtuedString.Key的数组,但从未编译过。我该如何做才能在indexPath.item上获得正确的值?还是这完全是错误的方法?
let cellColor = [
NSAttributedString.Key.foregroundColor: UIColor.blue
NSAttributedString.Key.foregroundColor: UIColor.red
...
最终,我希望将数据保存在plist或json文件或核心数据中,但是(我相信)仍需要将数据加载到数组中(我相信)以通过indexPath.item访问。 / p>
我不太有经验,所以我可能缺少一些基本的知识。
答案 0 :(得分:1)
您必须创建一个数组来存储模型中的颜色,就像存储文本时一样
型号:
let myText = ["Pos.1", "Main Verb", "Pos.2".... etc
let myColors = [UIColor.blue, UIColor.red, UIColor.green.... etc
然后像这样
进行访问...
let text = myModel.myText[indexPath.item]
let color = myModel.myColors[indexPath.item]
let myAttributes: [NSAttributedString.Key : Any] = [.foregroundColor: color]
let myAttributedText = NSAttributedString(string: text, attributes: myAttributes)
...
请注意,您发布的不是数组,而是Dictionary。
另外,如果您只是更改文本颜色而不必使用NSAttributedString
,则可以更改标签的textColor
属性
编辑:
根据@Larme的建议,您还可以创建一个结构以将数据保存在模型中,因此只能有一个数组:
struct TextSettings {
let text: String
let color: UIColor
}
let myTextSettings = [TextSettings(text: "Pos.1", color: UIColor.blue),
TextSettings(text: "Main Verb", color: UIColor.red),
TextSettings(text: "Pos.2", color: UIColor.green), ...]
并在设置单元格时使用它
...
let settings = myModel.myTextSettings[indexPath.item]
let myAttributes: [NSAttributedString.Key : Any] = [.foregroundColor: settings.color]
let myAttributedText = NSAttributedString(string: settings.text, attributes: myAttributes)
...