突出显示 UILabel 中的子字符串

Highlighting a substring in a UILabel

我无法突出显示 substring.Here 是我所做的(是一个 "duplicate" 问题):

这是我需要将其转换为 NSRange

的地方
for user in tweet.userMentions
{          
    let userName = user.keyword
    if let startIndex = tweetTextLabel.text?.rangeOfString("@")?.startIndex
    {
        let range = startIndex...userName.endIndex
        var atrString = NSMutableAttributedString(string:tweetTextLabel.text!)
        atrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range as? NSRange)
        tweetTextLabel.attributedText = atrString
    }
}

我能做什么??也许这是 swift 的另一个功能 我正在使用 swift 1.1,iOS 8.1 SDK

更新 仍然没有突出显示文本

 for user in tweet.userMentions{

                let text = tweetTextLabel.text!
                let nsText = text as NSString
                let textRange = NSMakeRange(0, nsText.length)
                let attributedString = NSMutableAttributedString(string: nsText)

                nsText.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in

                    if (substring == user.keyword) {
                        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: substringRange)
                        println(substring)
                    }
                })
                tweetTextLabel.attributedText = attributedString
                println(attributedString)

再次更新 所以我更新代码的地方仍然没有为子字符串着色 我正在做一个推特应用程序,它用颜色标签、网址和用户屏幕名称突出显示

我不太明白你想做什么,但这里有一个供你工作的模型:

let s = "Eat @my shorts" as NSString
var att = NSMutableAttributedString(string: s as String)
let r = s.rangeOfString("@\w.*?\b", options: .RegularExpressionSearch, range: NSMakeRange(0,s.length))
if r.length > 0 {
    att.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: r)
}

这给出了一个属性字符串 "Eat @my shorts",其中单词“@my”是红色的。

希望提供线索...

更新@matt 的精彩回答,Swift 4:

 let s = "Eat @my shorts" as NSString
 let att = NSMutableAttributedString(string: s as String)
 let r = s.range(of: "@\w.*?\b", options: .regularExpression, range: NSMakeRange(0,s.length))
    if r.length > 0 { att.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: r)
        }

在 swift 4 中查找此扩展程序:

extension UILabel {

    func highlight(searchedText: String?, color: UIColor = .red) {
        guard let txtLabel = self.text?.lowercased(), let searchedText = searchedText?.lowercased() else {
            return
        }

        let attributeTxt = NSMutableAttributedString(string: txtLabel)
        let range: NSRange = attributeTxt.mutableString.range(of: searchedText, options: .caseInsensitive)

        attributeTxt.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)

        self.attributedText = attributeTxt
    }

}

编辑: 扩展改进,他可以接收 String

的参数
 extension UILabel {

    func highlight(searchedText: String?..., color: UIColor = .red) {
        guard let txtLabel = self.text else { return }

        let attributeTxt = NSMutableAttributedString(string: txtLabel)

        searchedText.forEach {
            if let searchedText = [=11=]?.lowercased() {
                let range: NSRange = attributeTxt.mutableString.range(of: searchedText, options: .caseInsensitive)

                attributeTxt.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
                attributeTxt.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: self.font.pointSize), range: range)
            }
        }

        self.attributedText = attributeTxt
    }

}

Swift5 版本,适用于 FontColor

extension UILabel {
    func highlight(text: String?, font: UIFont? = nil, color: UIColor? = nil) {
        guard let fullText = self.text, let target = text else {
            return
        }

        let attribText = NSMutableAttributedString(string: fullText)
        let range: NSRange = attribText.mutableString.range(of: target, options: .caseInsensitive)
        
        var attributes: [NSAttributedString.Key: Any] = [:]
        if let font = font {
            attributes[.font] = font
        }
        if let color = color {
            attributes[.foregroundColor] = color
        }
        attribText.addAttributes(attributes, range: range)
        self.attributedText = attribText
    }
}