gpt4 book ai didi

ios - 如何存储和访问 'array' 的 NSAttributedString.Key.foregroundColor 值

转载 作者:行者123 更新时间:2023-11-28 23:33:01 33 4
gpt4 key购买 nike

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

grid

对于文本,我有一个字符串值数组,我通过 cellForItemAt indexPath 中的 indexPath.item 调用该数组。但我不知道如何创建等效的属性值数组。

型号: let myText = ["Pos.1", "主要动词", "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 访问。

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

最佳答案

你必须创建一个数组来存储你的模型中的颜色,就像你的文本一样

型号:

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)
...

关于ios - 如何存储和访问 'array' 的 NSAttributedString.Key.foregroundColor 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55918449/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com