DeyaEldeen DeyaEldeen - 2 months ago 27x
iOS Question

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 tappable, like a
, 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)


If you want to get rid of the underline, best way to do this is to follow the advice that DeyaEldeen gave in the comment.

If you go to the .m file of FRHyperLabel, go to this method

- (void)checkInitialization {
    if (!self.handlerDictionary) {
        self.handlerDictionary = [NSMutableDictionary new];

    if (!self.userInteractionEnabled) {
        self.userInteractionEnabled = YES;

    if (!self.linkAttributeDefault) {
        self.linkAttributeDefault = @{NSForegroundColorAttributeName: FRHyperLabelLinkColorDefault,
                                      NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};

    if (!self.linkAttributeHighlight) {
        self.linkAttributeHighlight = @{NSForegroundColorAttributeName: FRHyperLabelLinkColorHighlight,
                                        NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};

And you can just remove this

NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)

from the attributes