将TextView.attributedText设置为NSATTRIBUTEDSTRING值的数组通过UserDefaults Swift

发布于 2025-02-02 18:03:20 字数 2600 浏览 2 评论 0原文

我被困。

我设置了一个阵列,如下所示:

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

然后在我希望在文本视图中显示属性text的视图中,我设置了代码,如下所示:

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

    
}

打印语句的结果告诉我,该数组正在通过并返回为这是:

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

},

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

},

但是我的文本视图没有任何内容,只是打印出我告诉您文本视图的内容是:可选()

我觉得我缺少一个基本在获取数据数组和以正确的方式分配到textView.attribatedstring之间,

如果我不传递数组,并且只需传递在文本视图中显示的单个属性ststring值。但是显然,我希望所有的单词都显示出来,并且我对如何实现这一目标完全陷入困境。

有什么想法吗?

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:

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红颜悴 2025-02-09 18:03:21

您正在保存一个数组并将其施放为NSATTRIBETDERSTRING,这将为您提供零。您希望所有单词在textview中显示为绿色,如果匹配绿色,则不会创建多个属性弦乐,而是使用:

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

对所有您想着色的句子执行此操作,而不创建新的mutableAbeatTribatedString(使用同一实例),然后保存mutableAttributedString.AttributedString()在UserDefaults中

You are saving an array and casting it as NSAttributedString which will give you 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:

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

゛时过境迁 2025-02-09 18:03:20

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

songlyricsricsultstext.attributedtext = rection as rection? NSATTRIBUTEDSTRING

应该是

songlyricsRicsultStext.attributedText = rectored as? [NSATTRIBUTEDSTRING]

- update---

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

尝试过

您是否

You are storing data in NSAttributedString array but you are restoring in NSAttributedString object. 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:

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

because restored data is of type Any

Thanks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文