Link within label in Swift

37,466

Solution 1

For such a case, instead of adding it as a UILabel component, I would rather use UITextView, because it has dataDetectorTypes property:

The types of data converted to tappable URLs in the text view.

You can use this property to specify the types of data (phone numbers, http links, and so on) that should be automatically converted to URLs in the text view. When tapped, the text view opens the application responsible for handling the URL type and passes it the URL. Note that data detection does not occur if the text view's isEditable property is set to true.

So, you can implement it as:

// as mentioned in the documentation, make sure to let it be uneditable:
textView.isEditable = false
textView.dataDetectorTypes = .link

For your case, I assume that it shall be .link. I would also suggest to check the other options for the UIDataDetectorTypes.

Solution 2

Use Active-Label https://github.com/optonaut/ActiveLabel.swift Make a UILabel named label

 let customType = ActiveType.custom(pattern: "\\sjohncena\\b") //Looks for "supports"
 label.enabledTypes.append(customType3)
 label.handleCustomTap(for: customType) { self.alert("Custom type", message: $0) }

 func alert(_ title: String, message: String) {
        let vc = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        vc.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
        present(vc, animated: true, completion: nil)
    }

where johncena is string which is clickable. see https://github.com/optonaut/ActiveLabel.swift/blob/master/ActiveLabelDemo/ViewController.swift

Solution 3

You can use TTTAttributedLabel to make a particular part or word tappable in a UILabel.

For example

label.text = @"Fork me on GitHub! (https://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range];

In addition to hyperlinks you can add custom links also to a particular part or word and that word becomes tappable and on tapping that word delegate method didSelectLinkWithURL gets called and you can check for that link inside that function

(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    NSLog(@"link %@", [url absoluteString]);
    NSLog(@"whole label %@", label);
}
Share:
37,466
KevinB
Author by

KevinB

Updated on July 09, 2022

Comments

  • KevinB
    KevinB almost 2 years

    I would like to do that in my app :

    enter image description here

    The label is like : username comment

    I don't know how to add the "button" within the label; I found this library but I'm not sure it will work? https://github.com/optonaut/ActiveLabel.swift

    Maybe use it by creating a regex for the first word? What do you think?