Parsing text from plist to NSAttributedString

2019-02-14 15:51发布

问题:

I'm loading in text from a plist and displaying it within my app. Ideally I want to be able to specify more complex formatting such as italics, bold and superscript text, and display it in a custom label such as TTTAttributedLabel.

Are there any available libraries to parse a string in a given format (preferably a simple text format such as Markdown or Textile) into an NSAttributedString? I am aware that solutions are available for parsing RTF and HTML, but this is overkill for my needs - plus I'd like the text to be easily written by hand.

Edit: this is for iOS/UIKit

回答1:

I've just added an NSString to NSAttributedString lightweight markup parser to MGBoxKit. It's not Markdown or Textile but it's very similar. So far it supports bold, italics, underline, monospacing, and coloured text.

The MGMushParser class could be used standalone, and is fairly easy to extend.

NSString *markup = @"**bold**, //italics//, __underlining__, and `monospacing`, and {#0000FF|coloured text}";

UIFont *baseFont = [UIFont fontWithName:@"HelveticaNeue" size:18];
UIColor *textColor = UIColor.whiteColor;

myLabel.attributedString = [MGMushParser attributedStringFromMush:markup
                               font:baseFont color:textColor];

OHAttributedLabel also has a similar markup parser.



回答2:

Caught your edit. For iOS/UIKit there is a project out there called NSAttributedString+HTML that attempts to simulate the functionality available on OS X. On OS X, you would just use some minor HTML to format the string and then parse it into NSAttributedString (or objects, or websites, or files, etc.).

The project I mentioned above attempts to offer the same extensions on iOS. I don't know why, after 6 major releases of iOS, it still lacks such rich tools and pushes all the weight on UIWebView (over WebKit) but that's how it is.