Nate Stedman

NSParagraphStyle+With

January 28th, 2016

I wrote Attributed to make attributed strings in Foundation more expressive. It works well with many attributes, including fonts and colors, because those values are represented by a single simple object. However, the paragraph style attribute contains a number of different properties. By default, the best way to create a paragraph style is to create a mutable version and set its properties. As this requires multiple expressions, it can’t be used inline with other attribute functions, without embedding it within a closure, which is also unnecessarily verbose.

To solve this, I’ve written a simple extension function for NSParagraphStyle, called with. It takes all of the properties that can be set on a mutable paragraph style as parameters, all of which have default values, so only the necessary properties need to be specified, like so:

let style = NSParagraphStyle.with(alignment: .Center, lineSpacing: 12)

Available on Github.