iOS equivalent to MacOS NSAttributedString initWithRTF

杀马特。学长 韩版系。学妹 提交于 2020-01-05 07:06:10

问题


What is an iOS equivalent to MacOS NSAttributedString initWithRTF ?

The Application Kit extends Foundation’s NSAttributedString class by adding support for RTF, RTFD, and HTML (with or without attachments), graphics attributes (including font and ruler attributes), methods for drawing attributed strings, and methods for calculating significant linguistic units.

- (id)initWithRTF:(NSData *)rtfData documentAttributes:(NSDictionary **)docAttributes

I need to process a short stream of RTF data in an iOS application. Thank you!


回答1:


There is no equivalent in iOS. The iOS version of NSAttributedString has only the functionality needed by CoreText, and CoreText itself has only the functionality needed by the UI classes, and this does not include RTF processing.

As far as I know, at least as of 5.0, UIWebView is the only way to process RTF. See https://developer.apple.com/library/ios/#qa/qa1630/_index.html. That may have changed with 5.1, because some of Apple's other apps seem to handle rich text now (but then again, those apps may have just changed from UITextView to UIWebView…).


UIWebView doesn't give you any way to access the attributed text from the RTF, because the web view never builds attributed text—instead, it builds HTML and CSS.

The good news is that this HTML and CSS is available in the DOM. At least for some types, this isn't true—all you see is an opaque wrapper that gets rendered by some magic code inside WebKit that you can't access—but RTF is not one of those types.

Using Safari Web Inspector, I opened up a sample RTF file on my iPhone, and looked at the DOM. It's full of nodes like this:

<span class="s2"><span class="bumpedFont16">m a test file. This is some </span></span>
<span class="s3"><span class="bumpedFont16">bold</span></span>

… where those classes are defined with inline <style> tags immediately before the tag they're first used in.

So, if walk the nodes that have text, that text is like an attributed character range (although if you actually want the start and end indices you'll need to count them up yourself…), and its computed style is roughly like an attribute dictionary. Of course "roughly like" isn't "identical"; a computed style looks like this:

direction: ltr; display: inline; font-family: 'Times New Roman'; font-size: 22px;
font-weight: bold; height: auto; margin-bottom: 0px; margin-top: 0px;
padding-right: 0px; text-align: left; width: auto;

So, not actually compatible with NSAttributedString, and not nearly as nice (unless your end goal is to create HTML, of course)… but at least something you can use.



来源:https://stackoverflow.com/questions/10920678/ios-equivalent-to-macos-nsattributedstring-initwithrtf

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