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

As architecture pattern of the app was chosen the MVVM design pattern, because the conversion of model data to a format convenient for presentation is a ViewModel task.

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

As you can see ViewModel contains properties hyperlinks (tuple with hyperlink text and url) and highlighted (tuple with words which would be highlighted and specified attributes for highlighting). Highlighting attributes taken out also as private properties.

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


If you noticed, an UIFont.preferredFont(forTextStyle: .body) is used as font of text. This is Apple’s recommendation to use the Dynamic Type.

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.




Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ace Rodstin

Ace Rodstin

More from Medium

How UIKit’s Auto Layout works and why it matters

Apple Developer Documentation’s Simple, Fundamental Design Flaw

Swift Essentials | Enums

D V N C I — A Storyboardless & Clean & Multidirectional Architecture