DeyaEldeen DeyaEldeen - 3 months ago 52x
Swift Question

how to turn some parts of UILabel to act like a UIButton?

I have an attributed string

, I was able to color some parts of the text

let text = "Why did \(event) give \(event2) a 5 stars review? Details here. "
let linkTextWithColor = "Why did"
let range = (text as NSString).rangeOfString(linkTextWithColor)
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor() , range: range)
labelEvent.attributedText = attributedString

now I want to make some parts of the text clickable, like a UIButton, how to do this ?

example 1

example 1

example 2

example 2

I need to have blue text to be responding to touch, and to run a specific function, like a
help is really appreciated, thanks.


I recommend you try this library out

Great library, easy to use and has few built in examples for you to try out. Examples are in both Objective-c and Swift

Example in Swift

 let str = "This is a random bit of text"
        let attributes = [NSForegroundColorAttributeName: UIColor.blackColor(),
                          NSFontAttributeName: UIFont.systemFontOfSize(15)]
        confirmLabel.attributedText = NSAttributedString(string: str, attributes: attributes)

        let handler = {
            (hyperLabel: FRHyperLabel!, substring: String!) -> Void in

            //action here
        //Step 3: Add link substrings
        confirmLabel.setLinksForSubstrings(["random"], withLinkHandler: handler)