The following article is also available on my blog.
First release of SwiftRichString was take place in December 2016; as many other works it’s born for my own needs; NSAttributedString management is one of the part of UIKit which owes lots from the Objective-C heritage and even if something is changed with Swift 4 it still have plenty room of improvement to fit well in a post Swift world.
SwiftRichString introduced the concept of Style to define and collect a type safe collection of attributes you can apply to a plain or already-attributed string. The new 2.x branch is a total rewrite of the library which suits better with protocol oriented programming approach with several room for future improvements.
Main highlights includes:
My first goal was to create a generic protocol (called StyleProtocol) with several methods which allows to apply the style’s attributes to plain/attributed string. From this protocol I’ve created three different concrete classes:
All of these elements can be also mixed to produce a single attributed string because — in fact — each instance just produce a dictionary of NSAttributedStringKey keys and value.
Since 2.x SwiftRichString introduces the concept of global styles register; its a singleton class where you can register styles (simple style, group or regex style) with an unique identifier.
Once registered style can be reused to render text from inside UI controls or via code.
Suppose we want to create a MyStylee style which allows to render a text with a common style and two variants identified by h1 and h2 tags.
The following code create three style and register its group to the global registry.
In order to keep our code clean we can define a non-instantiable struct to contains all registered style names:
Since now we can reuse it via code everywhere inside your app:
You can also set the style per UI control. In this example we assign MyStyle as the style for an UILabel ; once the label has a style assigned the content is rendered automatically with that style and you can update it by keeping the rendering by using styledText instead of attributedText .
Tag based rendering is useful but you can also apply regular expression matching style to a string. This is done by creating an instance of the StyleRegEx object:
That’s the result:
Concatenation between plain String and Attributed String is super-easy with SwiftRichString as using the + operator!
Want to know more about all the opportunities of SwiftRichString? On GitHub project’s page you can found the complete documentation of all features of the project. SwiftRichString is available for all Apple’s platforms and can be installed via CocoaPods, Swift PM or Carthage.
Learn more about how to manage #NSAttributedString in #Swift using the new #SwiftRichString 2! https://t.co/iLIvO9u5jK #swift #swiftlang #iosdev
Powered by WPeMatico