iOS - Swift how to make links clicked in UILabel
Solution 1
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.
Solution 2
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
Solution 3
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
Comments
-
naiyu almost 2 years
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 } }
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.