【发布时间】:2018-03-14 12:50:38
【问题描述】:
我想替换字符串中的所有特定单词。
例如)
var str = "apple is red. apple is green"
我只想改变句子中“apple”这个词的背景。
所以我尝试了以下方法。
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"
我想要结果 -> “苹果(改变背景颜色)是红色的。苹果(改变背景颜色)是绿色的。
我该怎么办?
【问题讨论】:
-
range(of:)将只返回第一次出现,这是正常行为。您需要循环或正则表达式。 -
@Larme 我明白这一点。但我不知道如何实现...
-
@Larme OMG。很好的工作。非常感谢!!!!
标签: swift string nsstring nsattributedstring