Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give UITextView a clickable URL link

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

like image 577
BigBurger Avatar asked Sep 05 '25 03:09

BigBurger


2 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'.

like image 137
Habibur Rahman Avatar answered Sep 08 '25 00:09

Habibur Rahman


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
like image 41
Ailsa Avatar answered Sep 07 '25 22:09

Ailsa