NSAttributedString and Links on iOS

 ̄綄美尐妖づ 提交于 2019-11-28 19:51:55

Jeremy has published JTextView, a Core Text-based UITextView analogue that supports attributed text, including links.

In a nutshell, JTextView:

  • Creates its own attribute for links by using a custom name for the attribute name and the attribute value contains a representation of the corresponding URL
  • In -drawRect:, it uses a data detector for links. If a link has been found, it sets its custom attribute for the corresponding range
  • In its tap gesture recogniser method, it gets the line frame that contains the tap point. For each glyph run in that line, it gets its attributes and checks whether they contain the custom attribute for links. If so, it opens the URL.

As of iOS 7, UITextView supports links in attributed strings:

textView.attributedText = [[NSAttributedString alloc] initWithString:@"Stack Overflow" attributes:@{NSLinkAttributeName: @"http://stackoverflow.com"}];

By default, links are rendered as blue text. You can change the style with UITextView's linkTextAttributes property.

If you set editable to NO on the UITextView, links become tappable.

Ray Mckaig

I know this is an old question, but...

Try using NSMutableAttributedString. It has two methods for attributes:

void addAttribute:(NSString *)value range:(NSRange)

and

void addAttributes:(NSDictionary *) range:(NSRange)

Use a UITextView, it will parse your text and turn links into blue underlined hyperlinks:

textView.dataDetectorTypes = UIDataDetectorTypeLink;

Yes it doesn't exist, if you reduce your search to iOS Library it won't give you any results for NSLinkAttributeName. It's not there...officially, maybe private?

This nice article mentions hyperlinks but does not show an example. I doubt that it's possible with public API methods.

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