我如何使用 NSAtributedString 在 UITextVIew 中突出显示具有多种颜色的单词?

How am I able to highlight words with multiple colors in UITextVIew with NSAtrributedString?

这个问题困扰我很久了。正如标题所说,我看不出有任何其他方法可以想出用各种颜色突出显示某些特定单词的想法。例如,如果我有一个包含单词的数组,"hello"、"awesome"、"hungry"、"sky"...等等。然后在下面的代码中,它只是用一种颜色突出显示数组中的这些单词,颜色由 NSBackgroundColorAttributeName 设置。所以到目前为止,我最好的解决方案是创建多个相同的方法,但失败了。所以我做了几个highlightColors方法,在每个方法中输入一个数组,并为每个方法改变不同的颜色。

在我的 TextView 上输入的一个词变成了蓝色。在我的 TextView 上输入另一个数组中的另一个词后,新输入的词变成红色,但前一个词不再突出显示。我希望来自不同数组的所有单词都以不同方式突出显示。我从不希望它们的颜色消失。我一个星期都想不出这个主意。你能帮我解决这个问题吗?

func highlightColors(type: [String]){

    let attrStr = NSMutableAttributedString(string: myTextView.text)

    let inputLength = attrStr.string.characters.count
    let searchString : NSArray = NSArray.init(array: type)
    for i in 0...searchString.count-1 {

        let string : String = searchString.object(at: i) as! String
        let searchLength = string.characters.count
        var range = NSRange(location: 0, length: attrStr.length)

        while (range.location != NSNotFound) {

            range = (attrStr.string as NSString).range(of: string, options: [], range: range)

            if (range.location != NSNotFound) {
                coloredStringArray.append(string)
                attrStr.addAttribute(NSBackgroundColorAttributeName, value: UIColor.blue, range: NSRange(location: range.location, length: searchLength))
                attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 20), range: range)
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
                myTextView.attributedText = attrStr
                myTextView.font = UIFont(name: "times new roman", size: 20.0)

            }
        }
    }
} 

下面是一个使用NSAttributedString 以特定颜色突出显示特定单词的示例。您可以根据需要使用特定字体和背景等突出显示任何方式对其进行修改。

想法是您在文本视图的文本中搜索字符串,然后使用所需的属性修改其属性字符串。

当您编辑 textView 时,您的属性可能消失的原因是因为您正在使用 textView.text = blah..

private var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.textView = UITextView()
    self.view.addSubview(self.textView)


    self.textView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    self.textView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
    self.textView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
    self.textView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

    self.textView.translatesAutoresizingMaskIntoConstraints = false

    self.textView.text = "Test Highlighting Colors on Whosebug."

    self.highlight(text: ["Test", "Highlighting", "Colors", "Whosebug", "Test"], colours: [UIColor.red, UIColor.blue, UIColor.green, UIColor.purple, UIColor.cyan])
}

func highlight(text: [String], colours: [UIColor]) {
    var ranges = Array<Int>()
    let attrString = self.textView.attributedText.mutableCopy() as! NSMutableAttributedString

    for i in 0..<text.count {

        let str = text[i]
        let col = colours[i]
        var range = (self.textView.text as NSString).range(of: str)

        while (range.location != NSNotFound && ranges.index(of: range.location) != nil) {
            let subRange = NSMakeRange(range.location + 1, self.textView.text.characters.count - range.location - 1)
            range = (self.textView.text as NSString).range(of: str, options: NSString.CompareOptions.literal, range: subRange)
        }

        if range.location != NSNotFound {
            ranges.append(range.location)
            attrString.addAttribute(NSForegroundColorAttributeName, value: col, range: range)
        }
    }

    self.textView.attributedText = attrString
}