NSAttributedString赢了';不要向字符串添加属性。(Swift 5)
我正在尝试使用以下命令为字符串中出现的字符串着色:NSAttributedString赢了';不要向字符串添加属性。(Swift 5),swift,string,xcode,nsattributedstring,nsmutableattributedstring,Swift,String,Xcode,Nsattributedstring,Nsmutableattributedstring,我正在尝试使用以下命令为字符串中出现的字符串着色: 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 color
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
}
}
扩展字符串{
func color2(
redText:[字符串],
orangeText:[字符串]
)->NSAttribute字符串{
let result=nsmutableAttributeString(字符串:self)
枚举子字符串(在:startIndex。。
我看不出这里有什么不同,为什么不起作用
问题只是你做出了一个奇怪的决定,一个字一个字地循环字符串。正斜杠是一个分词器,所以单词是
R09
27
R13
51
R22
08
R11
11
所有这些都与您的redText
或orangeText
字符串不匹配。没有匹配,就没有颜色。我想这是有道理的,为什么它可以在其他没有斜杠的应用程序上工作。我可以用什么循环来包括分隔符或带空格的循环?