以编程方式设置文本后,自动链接检测在 NSTextView 中不起作用
我有一个启用了自动链接检测的 NSTextView。当我以编程方式设置文本时 [myTextView setString:@"http://google.com"]
它不会自动显示链接。
如果我在文本视图中输入任何内容,它将添加链接。我希望它添加链接
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不得不花费一些时间寻找解决方案,但无法在任何地方找到它。
您不需要任何第三方库。可可会为你做的。
checkTextInDocument:仅适用于可编辑的文本视图(Apple 忘记提及这一点)。
如果你的 NSTextView 是只读的,这里的代码可以工作:
不要忘记检查 .xib 文件中的“智能链接”
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:
Do not forget to check "Smart links" in your .xib file
我最终添加了一个可以完成这项工作的类别。它依赖于其他几个类别来查找和格式化链接。
我在此处写了一篇关于它的博客文章。
我还在 GitHub 上放置了一个示例项目。
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.
如 Randall 网站上的评论,在 10.6 或更高版本中有一个简单的方法可以做到这一点:
根据视图的设置方式,这可能不仅仅是添加链接——例如它可以添加智能引号。您可以使用
setEnabledTextCheckingTypes:
来指定要检查的内容。就我而言,我希望在键入时启用智能引号,但我不希望在以编程方式更改文本时添加它们。所以我可以使用这样的东西:添加链接后,这将使字段恢复到之前的行为。
As noted in a comment on Randall's site, there is an easy way to do this in 10.6 or later:
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:That will return the field to its previous behavior after the links have been added.