ios - 在 UITextView 中着色 NSMutableAttributedString 给出奇怪的结果

标签 ios swift uitextview nsattributedstring nsmutableattributedstring

我正在尝试制作一个基本的 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]]

结果

screenshot

最佳答案

缺少单独字符的计数。

检查这个。

        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/

相关文章:

ios - 添加 UISearchController 后导航栏会变成白色

ios - 近距离放大时折线消失

ios - YouTube 嵌入视频无法启动

iphone - 当键盘出现时,如何在 iOS 上调整 UITextView 的大小?

ios - 如何在 UITextView 中找到光标的像素位置?

ios - 如何在 iPhone 4S Swift 上的 UITextView 中动态调整文本大小

ios - PaintCode - 在路径上移动对象

ios - 如何重用我构建的 View

ios - 在 Swift 中缓存静态函数结果?

ios - 如何从屏幕外为 ImageView 设置动画