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

1

6

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).

Erigena answered 18/5, 2015 at 10:5 Comment(0)
V
8

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.

Vaccine answered 18/5, 2015 at 10:15 Comment(3)
excellent! works that easily either via paragraphStyle.hyphenationFactor = 1 or via the UI.Erigena
This might not be the direct answer that I am looking for, but it looks really nice and will be what I will use. I will mark as answered if I don't get an answer that can retain the words and just lock the text tracking.Erigena
implemented in my solution, but if anyone still wants to answer, i'd like to know how to keep word wrap + kerning/tracking locked when justifying.Erigena

© 2022 - 2024 — McMap. All rights reserved.