我无法突出显示子字符串。这是我所做的(是一个“重复”问题::
这里是我需要将其转换为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
更新
仍然不是突出显示文字所以我在更新代码的地方仍然没有为子字符串着色我正在做一个Twitter应用程序,该应用程序使用颜色标签,URL和用户屏幕名称突出显示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)
另一个更新
我无法突出显示子字符串。这是我做的(是一个“重复”问题):这是我需要在其中将tweet.userMentions中的用户强制转换为NSRange的地方{let userName = user.keyword ...
我不太了解您要做什么,但这是您可以使用的模型:
快速查找此扩展名:
更新@matt的好答案,Swift 4: