Give UITextView a clickable URL link

Viewed 1426

Hi I've been on this problem for a while now, I read a couple of posts already an I can't understand how to make a clickable UITextView that sends on internet. Here is my code:

func transformText(text: String, underlined: Bool, linkURL: String) -> NSAttributedString {
    let textRange = NSMakeRange(0, text.characters.count)
    let attributedText = NSMutableAttributedString(string: text)
    if underlined{
        attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
        attributedText.addAttribute(NSUnderlineColorAttributeName , value: UIColor.lightGray, range: textRange)
    }
    attributedText.addAttribute(NSFontAttributeName , value: UIFont(name: "Helvetica-Light", size: 17)!, range: textRange)
    attributedText.addAttribute(NSForegroundColorAttributeName , value: UIColor.lightGray, range: textRange)
    if(linkURL != "")
    {
        let attrib = [NSLinkAttributeName: NSURL(string: linkURL)!]
        attributedText.addAttributes(attrib, range: textRange)
    }
    return attributedText
}

Here is how i call it:

TextContent.attributedText = transformText(text: self.TelBox.TextContent.text, underlined: true, linkURL: "https://www.google.fr")`

Thanks in advance

4 Answers

Select the UITextView on storyboard and go to 'Show the Attributes inspector', then in 'behavior' unselects 'Editable' and in 'Data Detector' select 'Link'. Then go to 'Sohw the Identity inspector' and in 'traits' select 'Link' and 'Selected'.

You must set editable YES or set selectable YES

NSString *text = @"this is google web link";
UITextView *textView = [[UITextView alloc] init];

NSDictionary *dictionary = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text attributes:dictionary];

textView.attributedText = attributeStr;

[attributeStr addAttributes:@{NSLinkAttributeName: [NSURL URLWithString:@"http://www.google.com"]} range:[_readMessage rangeOfString:@"google web link"]];
textView.attributedText = attributeStr;

textView.editable = NO;
textView.selectable = YES;
textView.delegate = self;

google link will reponse by delegate

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange

The fact is you want to make UITextView to make clickable requires you to make UITextView non editable because when you click on text it will lunch keyboard. To prevent this you can use

textView.isEditable = false

Hope it helps.

Make sure you've also enabled data type detection. For hyperlinks:

theTextView.dataDetectorTypes = [.link]
Related