How to format usual string, creating links and highlighting words.

Hello. It is nice practice — to format text of loaded model and bring to user spiffy look. Most often, the design of the text is to use a NSMutableString and a huge number of attributes. This post describes a simple algorithm for searching the right words in the text and assign them certain attributes. Let’s get started.

Project structure

Project structure

The app is pretty simple. There are one screen with background image and a UITextView on the top. As a model used a short article from… I think you guess where it comes from. And of course, the main work on processing the appearance of the text is concentrated in ViewModel.

Text formatting

Thus you can edit each highlighting attribute from one place.

Now need to find in text all hyperlinks and set them links attributes and then find in text all highlighting fragments and set them highlighting attributes. Searching algorithm is snappy and simple:

  • two variables for processed piece of text and not processed piece of text are crated for saving searching progress;
  • range of desired fragment is searching in the not processed piece of text;
  • attributes are set for text (NSMutableAttributedString) in this range.

And at the and of it all the attributed (formatted) text is set to UITextView (or it could be UILabel).

The end result of formatting

Conclusion

And if it necessary to make the Dynamic Type as bold or as italic, then use an extension for UIFont:

Thanks for this approach to:

If you want to see the all project, you can find link to it in the end of this post. And that’s all for today. See you again.