Automatic Link Detection not working in NSTextView

2020-07-08 06:45发布

问题:

I have an NSTextView with automatic link detection enabled. When I set the text programmatically [myTextView setString:@"http://google.com"] it doesn't automatically show the link.

If I type anything into the text view it will add the link. I want it to add the link

回答1:

Had to spent some time searching for solution, but could not find it anywhere.

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

checkTextInDocument: works only on editable textViews (Apple forgot to mention this). Here is code which works if your NSTextView is read only:

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

Do not forget to check "Smart links" in your .xib file



回答2:

I ended up adding a category that would do the job. It relies on a couple other categories for finding and formatting links.

I wrote a blog post about it here.

I also put a sample project up on GitHub.



回答3:

As noted in a comment on Randall's site, there is an easy way to do this in 10.6 or later:

[self.textView checkTextInDocument:nil];

Depending on how the view is set up, this may do more than just add links—for example it could add smart quotes. You can use setEnabledTextCheckingTypes: to specify what you want to check. In my case, I want to have smart quotes enabled while typing, but I don't want them added when I'm programmatically changing the text. So I can use something like this:

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

That will return the field to its previous behavior after the links have been added.