gpt4 book ai didi

swift - 如何快速将特定单词替换为 NSAttributedString

转载 作者:行者123 更新时间:2023-11-28 14:56:47 24 4
gpt4 key购买 nike

<分区>

我想替换字符串中的所有特定单词。

例如)

var str = "apple is red. apple is green"

我只想在句子中更改“苹果”一词的背景。

所以我尝试了以下方法。

let resultString = NSMutableAttributedString(string: str)

let apple = NSMutableAttributedString(string: "apple")

apple.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.yellow, range: NSRange(location: 0, length: apple.length))

resultString.replaceCharacters(in: (str as NSString).range(of: "apple"), with: apple)

但结果是这样。

resultString = "apple(change background color) is red. apple(did not change background color) is green"

我想要结果 -> "apple(change background color) is red. apple(change background color) is green.

我该怎么办?

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