iOS - Swift how to make links clicked in UILabel
Asked Answered
W

5

6

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.

Wrapping answered 2/6, 2016 at 17:34 Comment(0)
J
0

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.

Jarietta answered 2/6, 2016 at 17:43 Comment(0)
P
1

The short answer is UILabel's don't support opening URL's. It can detect that the link exists, but it won't do anything.

You can find alternatives to a solution to your problem, and you can read about that here

Purapurblind answered 2/6, 2016 at 17:40 Comment(0)
F
1

It is highly recommended to use a UITextView object rather than a UILabel, however you could make use of the KILabel project as a UILabel alternative. See https://github.com/Krelborn/KILabel/blob/master/README.md

Forehead answered 2/6, 2016 at 20:23 Comment(0)
A
1

This is a Basic approach for your needs, i used to us for creating a clickable labels

private let linkLabel: UILabel = {
    let label = UILabel()
    label.text = "Link"
    return label
}()

  func setup() {
        linkLabel.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(openLink))
        linkLabel.addGestureRecognizer(tap)
}

    if let openLink = URL(string: "http://www.apple.com") {
    if UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url, options: [:])
    }
}
Arianna answered 14/11, 2021 at 10:1 Comment(0)
J
0

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.

Jarietta answered 2/6, 2016 at 17:43 Comment(0)
B
0

For links, generally the correct answer is to use UITextView.

But I understand that the extra two subviews can be a bit heavy for simple use cases. The UILabel subclasses are fine, but then you’re restricted from using your own subclass. The other answers all rely on recreating your own text stack hoping to mimic the one used by UILabel, though that fails quickly when the text starts to shrink.

Because of all this, I’ve created LinkGestureRecognizer (https://github.com/stuartjmoore/UILabel-LinkGestureRecognizer) for all your UILabel needs.

It’s as simple as:

let label = UILabel()
label.attributedText = // An attributed string with inline link ranges

let linkGestureRecognizer = LinkGestureRecognizer(target: self, action: #selector(handleLinkTap))
label.addGestureRecognizer(linkGestureRecognizer)

@objc func handleLinkTap(_ gestureRecognizer: LinkGestureRecognizer) {
    // handle gestureRecognizer.url in gestureRecognizer.range (UTF-16)
}
Bellabelladonna answered 15/1, 2022 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.