Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Justify text in iOS (Swift or Objective-C) without breaking tracking/kerning/letter spacing

Tags:

ios

uikit

justify

See below:

// Description (HTML string):
var attrStr = NSMutableAttributedString(
    data: formatted.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
    options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
    documentAttributes: nil,
    error: nil)

var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Justified
attrStr?.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attrStr!.length))
attrStr?.addAttribute(NSKernAttributeName, value: -0.1, range: NSMakeRange(0, attrStr!.length))
descLabel.attributedText = attrStr
descLabel.sizeToFit()

So far all my attempts to justify text, result in the very same behavior. I've tried via inline-style CSS int eh html text, or using textAlignment property.

The issue is, justifying the text breaks the letter spacing (actually it increases the tracking/kerning of each word instead of only increasing the space in-between).

See: enter image description here

I would like so see a solution that is not a hack, since I have devised some hacks of my own but then I fall into too many possibilities for other issues.

I'm I missing something simple? I've been through all the UI options and as seen in my code sample, I even tried changing the Kern, which does change but only in proportion (i.e. it still increases).

like image 271
ericosg Avatar asked May 18 '15 10:05

ericosg


1 Answers

Have you tried adding a NSParagraphStyle attribute with hyphenationFactor of 1?

This will keep your kerning and word spacing, but will add hyphenation when the word needs to break to the next line.

like image 135
Enrico Susatyo Avatar answered Nov 03 '22 00:11

Enrico Susatyo