设置textView.通过UserDefaults swift将attributedtext转换为NSAttribute



我卡住了

我建立了一个数组,如下所示:

private var lyricArray : [NSAttributedString] = []

我有一个有比赛和失误的游戏。对于每一个匹配,我希望文本的颜色是绿色,没有的是红色。

我将代码设置如下:

if isMatch == true {
secondBody.node?.run(colorTransition(fromColor: .init(customName: .brandWhite), toColor: .init(customName: .brandGreen)))
for lyric in songLyrics {
let red = UIColor.init(customName: .brandGreen)
let attributedStringColor = [NSAttributedString.Key.foregroundColor : red]
let lyricColor = NSAttributedString(string: lyric!, attributes: attributedStringColor)

lyricArray.append(lyricColor)

print("Your lyric array looks like this: (lyricArray)")
do {
//if i set the root object to lyricColor it will show it in the resulting text view
let data = try NSKeyedArchiver.archivedData(withRootObject: lyricArray, requiringSecureCoding: false)

defaults.set(data, forKey: "SavedLyrics")
} catch {
print(error)
}



}

然后在我希望在文本视图中显示attributedText的视图中设置如下代码:

private func showUserLyrics() {
let defaults = UserDefaults.standard
let stringData = defaults.data(forKey: "SavedLyrics")

do {
let restored = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, NSAttributedString.self], from: stringData!)

songLyricsResultsText.attributedText = restored as? NSAttributedString
//homeLabel.attributedText = restored as? NSAttributedString
print("Contents of songlyrics is as follows(String(describing: restored))")
print("I'm telling you the contents of your text view is:(String(describing: songLyricsResultsText.attributedText))")

} catch {
print(error)
}

}

print语句的结果告诉我数组正在被传递,并返回如下:

was{
NSColor = "<UIDynamicCatalogColor: 0x282d27ed0; name = brandRed>";

},

the{
NSColor = "<UIDynamicCatalogColor: 0x282d45bd0; name = brandGreen>";

},

但是我的textView没有这些只是打印出I'm telling you the contents of your text view is:Optional()

我觉得我错过了获得数据数组和以正确的方式分配给textview.attributedstring

之间的基本步骤如果我不传入数组只传入单个attributedString值它会显示在文本视图中。但是很明显,我想要显示所有的单词,而我完全不知道如何实现这一点。

任何想法吗?

您正在NSAttributedString数组中存储数据,但您正在NSAttributedString对象中恢复数据。我认为这是你的代码的问题而不是

songLyricsResultsText.attributedText = restored as? NSAttributedString

应该

songLyricsResultsText.attributedText = restored as? [NSAttributedString]

——更新你试过了吗:

let lyricsArray = restored as? [NSAttributedString]    
songLyricsResultsText.attributedText = lyricsArray[0]

,因为恢复的数据类型为Any

感谢

你正在保存一个数组并将其转换为NSAttributedString,这将给你nil。如果您希望所有的单词在textView中显示为绿色,如果它匹配,那么您不需要创建多个attributedstring,而是使用:

let range = (lyric as NSString).range(of: theSentenceYouWantToColor)
let mutableAttributedString = NSMutableAttributedString(string: theTextContainingTheSentence)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: yourColor, range: range)

在不创建新的mutableAttributedString(使用相同的实例)的情况下为所有想要着色的句子执行此操作,然后将mutableAttributedString.attributedString()保存在UserDefaults

中。

最新更新