Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting a substring in a UILabel

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

like image 639
Stefan Scoarta Avatar asked Apr 17 '15 18:04

Stefan Scoarta


People also ask

How to render bold text in uilabel or UITextView?

To render this text properly in UILabel or UITextView, you need to convert it to NSAttributedString. NSAttributedString has built-in support for this conversion. First, we need to convert HTML string to Data. let htmlString = "This is a <b>bold</b> text." let data = htmlString.data(using: .utf8)!

How do I add a label to an interface?

Follow these steps to add a label to your interface: Supply either a string or an attributed string that represents the content. If you’re using a nonattributed string, configure the appearance of the label. Set up Auto Layout rules to govern the size and position of the label in your interface.

How do I customize the text of an NSAttributedString?

Figure 1 shows a label displaying an NSAttributedString that includes attributes to customize the font, color, and alignment of the string. If you want to format the label’s text in a uniform fashion, set the text property to an NSString object containing the content, and configure the font, textColor, textAlignment, and lineBreakMode properties.

How do I make a label use multiple lines of text?

Setting a value of 0 allows the label to use as many lines as necessary to lay out the text within the label’s width. Use the lineBreakMode property to control how the label splits the text into multiple lines, and the truncation behavior associated with the final line. Use Auto Layout to position and optionally size the label.


2 Answers

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.

enter image description here

Hope that provides a clue...

like image 105
matt Avatar answered Oct 26 '22 12:10

matt


Look for this extension in 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
    }

}

EDIT: Extension improved, he can receive arguments of 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 = $0?.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
    }

}
like image 45
Mickael Belhassen Avatar answered Oct 26 '22 10:10

Mickael Belhassen