2

1) I would like to add a link to a UITextView. I know that if I put a url like http://stackoverflow.com in my text, it will automatically be recognized as a link. But is there a way to have a link for a word, and not only for a url ? Like in HTML : <a href="http://stackoverflow.com ">stackoverflow</a>

2) I would like to custom this link, and especially its color, font type, etc. Is there a way to add a property only for the link ?

If all this is complicated, do you see any better way to do it easily ?

Thank you !

Nicolas Roy
  • 3,773
  • 5
  • 27
  • 42

4 Answers4

3

try this:

self.myTextView.dataDetectorTypes = UIDataDetectorTypeLink;
DharaParekh
  • 1,730
  • 1
  • 10
  • 17
1

It seams it's not possible to do what I wanted with UITextViews (at least not easily). The solution is to use a UIWebView instead and load a local HTML file with the text and the link. You can even put some CSS to customize the color, size ...

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    // webview
    webview.delegate = (id<UIWebViewDelegate>)self;
    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"fileName" ofType:@"html"];
    NSError *error;
    NSString *initialHTMLString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    [webview loadHTMLString:initialHTMLString baseURL:nil];

    webview.opaque = NO;
    webview.backgroundColor = [UIColor clearColor];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    if (navigationType == UIWebViewNavigationTypeLinkClicked) {

        [[UIApplication sharedApplication] openURL:[request URL]];

        return NO;
    }

return YES;

}

I hope this will help anyone having the same problem !

Nicolas Roy
  • 3,773
  • 5
  • 27
  • 42
  • Check BHUPI 's answer here, it does exactly what you want: http://stackoverflow.com/questions/2454067/display-html-text-in-uitextview – alasker Mar 05 '16 at 21:56
1
textView.dataDetectorTypes = .link
textView.isEditable = false
textView.isSelectable = true

let html = "<div style=\"font-family: 'Arial'; font-size: 20;\"><a href=\"http://www.stackoverflow.com\">stackoverflow</a></div>"

if let dataWithHTML = html.data(using: .utf8) {

    textView.attributedText = try? NSAttributedString(data: dataWithHTML, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
}
sash
  • 8,423
  • 5
  • 63
  • 74
0

Take a look at DTCoreText which offers a range of different views where you can use HTMLish input and customise the display and handling.

Wain
  • 118,658
  • 15
  • 128
  • 151