简体   繁体   中英

iOS: Best approach to parsing HTML and create attributed string and links from this?

I am looking for some advice on how to approach this problem.

I am getting a string from an API, which may contain HTML tags, such as italic text, bold text, links, images, paragraphs, etc.

I am probably going to go with TTTAttributedLabel which I generally have a lot of love for.

During parsing, I create a string from the original string which strips out all HTML tags. I am using NSString+HTML from a project for that and that seems to work great.

Now what I want to do is prepare an NSAttributedString that TTTAttributedLabel can use to display the text with the right formatting.

I also want to prepare links at the same time in a separate array.

I am wondering if Regex is the appropriate way to go, and how exactly I am going to achieve it.

With Regex, I could look for any HTML tags with <[^>]*> , however, I would like to know the text in between the tags.

Take the following string as an example:

The <b>quick</b> brown fox <i>jumps</i> over the <a href="http://dog.com">lazy dog</a>.

Which should display as:

The quick brown fox jumps over the lazy dog .

Now, what I then essentially want are NSRange s for each of the texts appearing inside tags and their type (but taking the tag out of the equation). So for example, for the text above I would get:

NSRange boldRange = NSMakeRange(4, 3);
NSRange italicRange = NSMakeRange(20, 5);
NSRange urlRange = NSMakeRange(35, 8);

I am thinking this should be done as a loop so that I can add formatting to the NSAttributedString I am creating and of course save out the URL ranges to a separate array so I can create the links during display.

Are there any libraries out there to assist me. I'll try to update this question as I find things.

您可以尝试OHAttributedLabel,它可以像您要​​求的那样显示html字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM