Search code examples
htmlswifttagsuilabel

iOS - Swift how to make links clicked in UILabel


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() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let attrStr = try! NSAttributedString(
            data: "This is a link <a href='http://www.google.com'>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:

  1. How to get the URL of the link.
  2. If there are more than one links, what I need to do.

Thanks for checking this question firstly.


Solution

  • 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:

    1. init

       - (instancetype)initWithFrame:(CGRect)frame {
         self = [super initWithFrame:frame];
           if (self)
           {
               //call the method to configure the button
               [self configure];
           }
         return self;
       }
      
    2. 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.