小编典典

快速上色所有出现的字符串

swift

此代码

var textSearch="hi"
var textToShow="hi hihi hi" 
var rangeToColor = (textToShow as NSString).rangeOfString(textSearch)
var attributedString = NSMutableAttributedString(string:textToShow)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor() , range: rangeToColor)
TextView.attributedText=attributedString

给了我NSRange为TextView内部的字符串着色。问题是我只返回第一次出现。如果单词包含“ hi hihi hi”,则仅第一个“
hi”会被上色。如何获得所有出现的字符串?


阅读 222

收藏
2020-07-07

共1个答案

小编典典

斯威夫特5

let attrStr = NSMutableAttributedString(string: "hi hihi hey")
let inputLength = attrStr.string.count
let searchString = "hi"
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
    range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
    if (range.location != NSNotFound) {
        attrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.yellow, range: NSRange(location: range.location, length: searchLength))
        range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
    }
}

迅捷3

let attrStr = NSMutableAttributedString(string: "hi hihi hey")
let inputLength = attrStr.string.characters.count
let searchString = "hi"
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
    range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
    if (range.location != NSNotFound) {
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow(), range: NSRange(location: range.location, length: searchLength))
        range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
    }
}

迅捷2

let attrStr = NSMutableAttributedString(string: "hi hihi hey")
let inputLength = attrStr.string.characters.count
let searchString = "hi"
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: attrStr.length)

while (range.location != NSNotFound) {
    range = (attrStr.string as NSString).rangeOfString(searchString, options: [], range: range)
    if (range.location != NSNotFound) {
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: NSRange(location: range.location, length: searchLength))
        range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
    }
}
2020-07-07