Automatic link detection does not work in NSTextView after programmatically setting text

I have an NSTextView with automatic link detection enabled. When I set the text programmatically [myTextView setString:@"http://google.com"] , it does not automatically display the link.

If I print anything in a text view, it will add a link. I want him to add a link

+7
source share
3 answers

In the end, I added a category that will do the job. It relies on a couple of other categories to search and format links.

I wrote a blog post about it here .

I also put a sample project on GitHub.

+6
source

I had to spend some time searching for a solution, but could not find it anywhere.

You do not need third-party libraries. Cocoa will do it for you.

checkTextInDocument: only works with editable text windows (Apple forgot to mention this). Here is the code that works if your NSTextView is read-only:

 [myTextView setEditable:YES]; [myTextView checkTextInDocument:nil]; [myTextView setEditable:NO]; 

Remember to check the "Smart Links" in your .xib file.

+8
source

As noted in a comment on the Randall website , in 10.6 or later there is a simple way:

 [self.textView checkTextInDocument:nil]; 

Depending on how the view is configured, this can do more than just add links - for example, it can add smart quotes. You can use setEnabledTextCheckingTypes: to indicate what you want to check. In my case, I want smart quotes to be included during typing, but I don't want them to be added when I change text programmatically. So I can use something like this:

 NSTextCheckingTypes oldTypes = self.textView.enabledTextCheckingTypes; [self.textView setEnabledTextCheckingTypes:NSTextCheckingTypeLink]; [self.textView checkTextInDocument:nil]; [self.textView setEnabledTextCheckingTypes:oldTypes]; 

This will revert the field to its previous behavior after adding links.

+4
source

All Articles