如何存储和访问NSAttributedString.Key.foregroundColor值的“数组”

问题描述 投票:0回答:1

我有一个网格UICollectionView在每个单元格中显示单个文本标签。虽然该图显示了每个单元格中的不同属性,但我无法弄清楚如何在NSAttributedString.Key.foregroundColor存储和访问特定的indexPath.item值。

grid

对于文本,我有一个字符串值数组,我通过cellForItemAt indexPath中的indexPath.item调用它。但我无法弄清楚如何创建一个等价的属性值数组。

型号:让myText = [“Pos.1”,“Main Verb”,“Pos.2”....等等

集合查看数据源:

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进行访问。

我不是很有经验,所以我可能会遗漏一些非常基本的东西。

ios uitableview uicollectionview nsattributedstring nsattributedstringkey
1个回答
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)
...
© www.soinside.com 2019 - 2024. All rights reserved.