在UITextView中着色NSMutableAttributedString会产生奇怪的结果

时间:2018-05-03 01:41:18

标签: ios swift uitextview nsattributedstring nsmutableattributedstring

我正在尝试制作一个基本的IDE /代码查看器,因此我试图为UITextView中的某些单词着色。我写了一个小循环来查找范围,另一个用于为NSMutableAttributedString范围内的单词着色。我知道范围正在被正确计算,因为代码末尾的print语句给出了正确的索引。但是我在应用程序中观察到一个非常奇怪的结果(下面的屏幕截图)。知道会出现什么问题吗?

CODE

    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]]

RESULT

screenshot

1 个答案:

答案 0 :(得分:0)

缺少单独字符的计数。

检查一下。

        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]))
        }

我希望能帮助它