我正在尝试制作一个基本的 IDE/代码查看器,因此我正在尝试为 UITextView
中的某些单词着色。我写了一个小循环来查找范围,另一个为 NSMutableAttributedString
范围内的单词着色。我知道范围的计算是正确的,因为代码末尾的打印语句给出了正确的索引。但是我在应用程序中观察到一个非常奇怪的结果(下面的屏幕截图)。知道可能出了什么问题吗?
代码
var ranges = [[Int]]()
var rcounter = 0
for word in content.components(separatedBy: [" ", "\n", "."]) {
if (word == "func") {
ranges.append([rcounter,rcounter+word.count])
}
rcounter += word.count
}
let attributedString = NSMutableAttributedString(string:content)
for range in ranges {
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:range[0],length:range[1])
}
textView.attributedText = attributedString
print(ranges) // [[0, 4], [288, 292]]
结果
最佳答案
缺少单独字符的计数。
检查这个。
var ranges = [[Int]]()
var rcounter = 0
let content = "func asdfasdfasdf. sdfdfdf12323 func adfadfasdf func() func. "
for word in content.components(separatedBy: [" ", "\n", "."]) {
if (word == "func") {
ranges.append([rcounter,word.count])
}
//add loop count on every loop time
rcounter += word.count + 1
}
let attributedString = NSMutableAttributedString(string:content)
for range in ranges {
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:range[0],length:range[1]))
}
希望能帮上忙
关于ios - 在 UITextView 中着色 NSMutableAttributedString 给出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50145773/