突出显示UILabel中的子字符串

问题描述 投票:3回答:3

我无法突出显示子字符串。这是我所做的(是一个“重复”问题::

这里是我需要将其转换为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 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)

另一个更新

所以我在更新代码的地方仍然没有为子字符串着色我正在做一个Twitter应用程序,该应用程序使用颜色标签,URL和用户屏幕名称突出显示

我无法突出显示子字符串。这是我做的(是一个“重复”问题):这是我需要在其中将tweet.userMentions中的用户强制转换为NSRange的地方{let userName = user.keyword ...

ios uitableview swift twitter
3个回答
10
投票

我不太了解您要做什么,但这是您可以使用的模型:


2
投票

快速查找此扩展名:


0
投票

更新@matt的好答案,Swift 4:

© www.soinside.com 2019 - 2024. All rights reserved.