简体   繁体   English

通过 UserDefaults swift 将 textView.attributedtext 设置为 NSAttributedString 值数组

[英]Setting textView.attributedtext to an array of NSAttributedString values through UserDefaults swift

I'm stuck.我被困住了。

I set up an array as follows:我设置了一个数组,如下所示:

    private var lyricArray : [NSAttributedString] = []

I have a game that has matches and misses.我有一个有比赛和失误的比赛。 For each match I want the color of the text to be green and red for a miss.对于每场比赛,我希望文本的颜色为绿色和红色,以防错过。

I set the code up as follows:我将代码设置如下:

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

Then in the view where I wish to display the attributedText in a text view I set up the code as follows:然后在我希望在文本视图中显示属性文本的视图中,我将代码设置如下:

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

    
}

The result of the print statements tells me that the array is being passed through and coming back as this: print 语句的结果告诉我,数组正在通过并返回,如下所示:

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

}, },

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

}, },

But my textView is having none of it and just printing out I'm telling you the contents of your text view is:Optional()但是我的 textView 没有,只​​是打印出来I'm telling you the contents of your text view is:Optional()

I feel like I'm missing a fundamental step between getting the array of data and assigning it in the correct way to the textview.attributedstring我觉得我在获取数据数组和以正确的方式将其分配给 textview.attributedstring 之间缺少一个基本步骤

If I don't pass in an array and just pass in the single attributedString value it will show in the text view.如果我不传入数组而只传入单个属性字符串值,它将显示在文本视图中。 But obviously I want all the words to show and I'm completely stuck as to how to make that happen.但显然我希望所有的话都显示出来,我完全不知道如何做到这一点。

Any thoughts?有什么想法吗?

You are storing data in NSAttributedString array but you are restoring in NSAttributedString object.您将数据存储在NSAttributedString数组中,但您正在恢复NSAttributedString对象。 I think this is the problem in your code instead of我认为这是您的代码中的问题,而不是

songLyricsResultsText.attributedText = restored as? NSAttributedString

should be应该

songLyricsResultsText.attributedText = restored as? [NSAttributedString]

--UPDATE-- did you try this: --UPDATE-- 你试过这个吗:

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

because restored data is of type Any因为恢复的数据是Any类型

Thanks谢谢

You are saving an array and casting it as NSAttributedString which will give you nil.您正在保存一个数组并将其转换为 NSAttributedString ,这将为您提供 nil。 You want all the words to show in the textView as green if it matches, then you don't create multiple AttributedStrings, instead you use:如果匹配,您希望所有单词在 textView 中显示为绿色,然后您不创建多个 AttributedStrings,而是使用:

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

do this for all the sentences you'd like to color while not creating a new mutableAttributedString (use the same instance), then you save the mutableAttributedString.attributedString() in UserDefaults在不创建新的 mutableAttributedString (使用相同的实例)的同时对所有要着色的句子执行此操作,然后将mutableAttributedString.attributedString()保存在 UserDefaults

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM