Piepants Piepants - 1 year ago 71
iOS Question

How do you add leading spacing to text?

I've got some requirements that text within an app must conform to company branding stipulations.
In particular the text must have tracking and leading values added to it.
Tracking doesn't exist in iOS but I found something on line for converting font tracking values to font spacing values.

However I can't find anything about adding leading to text. Here's a quote from the requirements:

".. for larger sizing (above 18pt), we also plug a +2 value of the type's point size into the leading". And there's also a table of fonts sizes used within the app and associated values to be used for the leading (30, 26, 20, 18, 12).

How do I apply these leading values to the text? I've tried searching for this but can't find very much at all.

I saw here http://kalyanchakravarthy.net/blog/using-nsattributedstring-on-ios.html
which says

"NSStringDrawingUsesFontLeading - font leading basically means line
spacing. This flag indicates the call to make use of default line
spacing specified by the font."

It says leading and spacing are the same, but this has confused me - implying that the only way to change the leading is to set the spacing, yet that conflicts with the requirements where the spacing is the same but the leading changes depending on the font point size.

Answer Source

I'd like to suggest you create an NSAttributedString subclass or category that has an added NSString property and a font size property (or an enum if you wish to name the various fonts, for example HeaderFont, ... which then defines size and possibly other attributes).

In the 'set' method of that NSString property you then put the code to setup the various attributes.

This way you hide all these nasty details, keeping them in one central place, and end up with a very simple class.

Could look something like:

UILabel* someLabel;

someLabel.attributedText = [[MyAttributedString alloc] initWithText:"Hello" font:HeaderFont];

Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download