I can;t highlight a substring.Here is what I done(is an "duplicate" question):
Here is where I need to cast it to 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
}
}
What can I do?? Maybe there it is another function thats for swift I'm using swift 1.1, iOS 8.1 SDK
Update Still isn't highliting the text
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)
Another update So where I updated the code still doesn't colour the substring I'm doing a twitter app that highlights with colors hashtags, urls and user screen names
I don't quite understand what you're trying to do, but here's a model for you to work from:
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)
}
That gives an attributed string "Eat @my shorts" where the word "@my" is red.
Hope that provides a clue...