0 0 0 0


This is my code that show the Links in a UILabel

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var textFiled: UITextField!
    @IBOutlet weak var label: UILabel!
    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.
        let attrStr = try! NSAttributedString(
            data: "This is a link <a href=''>google</a>".dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
        label.attributedText = attrStr

enter image description here

As you can see from the picture, it shows the link correctly that I just want it, but the link can't click to jump to a web view or others. Actually, I need to custom the link click event, and I really have no idea:

  • How to get the URL of the link.
  • If there are more than one links, what I need to do.
  • Thanks for checking this question firstly.

    Best Answer:

    As Luke said UILabels dont support URL's. But you can create a button to look like a label. Get rid of the background (so it looks like text )and implement the the function to the button to open the webview. You can use attributed strings to edit the style of the text in the button.

    You are going to want to look into using a custom class instead of the default uibutton class when you add the button to your UI.

    you will need to:

  • init

     - (instancetype)initWithFrame:(CGRect)frame {
       self = [super initWithFrame:frame];
         if (self)
             //call the method to configure the button
             [self configure];
       return self;
  • implement setTitle or setAttributedTitle if you are using an attributed string

     - (void) setTitle:(NSString *)title forState:(UIControlState)state
            [super setTitle:title forState:state]
  • or

          - (void)setAttributedTitle:(NSAttributedString *)title forState:   (UIControlState)state{
                [super setAttributedTitle:title forState:state];

    3. configure the button

             -(void) configure{
                 //configure the buttons label here 
                 //you will want to set no background colour

    4. add the button to viewcontroller and change the class to the custom class you created.

    Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs