Automatic Link Detection not working in NSTextView after programmatically setting text

半腔热情 提交于 2019-12-05 19:01:14

问题


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.



来源:https://stackoverflow.com/questions/7055131/automatic-link-detection-not-working-in-nstextview-after-programmatically-settin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!