我正在尝试使用以下方法为字符串中出现的字符串着色:
let text = "R09/27 R13/51 R22/08 R11/11"
let attributed = text.color2(redText: ["R09/27", "R11/11"], orangeText: ["R13/51"])
print(attributed)
textLabel.attributedText = attributed
以及以下扩展名:
extension String {
func color2(
redText: [String],
orangeText: [String]
) -> NSAttributedString {
let result = NSMutableAttributedString(string: self)
enumerateSubstrings(in: startIndex..<endIndex, options: .byWords) {
(substring, substringRange, _, _) in
guard let substring = substring else { return }
if redText.contains(substring) {
result.addAttribute(
.foregroundColor,
value: UIColor.systemRed,
range: NSRange(substringRange, in: self)
)
}
if orangeText.contains(substring) {
result.addAttribute(
.foregroundColor,
value: UIColor.systemOrange,
range: NSRange(substringRange, in: self)
)
}
}
return result
}
}
但是字符串不会变色。当我在控制台中打印属性时,它不会像通常那样显示任何属性,而是显示{}。有谁知道为什么我的文字不会为出现的情况涂上颜色?我以前在另一个应用程序中使用过此代码,并且工作正常,我看不到这里有什么不同以及为什么它不起作用。
我看不到这里有什么不同以及为什么不起作用。
问题仅仅是,您做出了这个奇怪的决定来遍历字符串by word。好吧,正斜杠是一个单词分隔符,所以这些单词是>>
R09 27 R13 51 R22 08 R11 11
这些都不是您的
redText
或orangeText
字符串的匹配项。没有匹配项,没有颜色。