开发者

Automatic Link Detection not working 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 doesn't automatically show the link.

If I type anything int开发者_如何转开发o the text view it will add the link. I want it to add the link


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜