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.
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.
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.
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).
If you noticed, an UIFont.preferredFont(forTextStyle: .body) is used as font of text. This is Apple’s recommendation to use the Dynamic Type.
Scaling Fonts Automatically
The Dynamic Type feature allows users to choose the size of textual content displayed on the screen. It helps users who…
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:
Extending UIFont to Make Fonts Bold or Italic in Swift
The sixth item in my Swift Tool Belt is an extension for UIFont. This extension will easily convert your font to be…
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.