Justify text in iOS (Swift or Objective-C) without

2019-02-10 06:28发布

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

1条回答
你好瞎i
2楼-- · 2019-02-10 06:57

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.

查看更多
登录 后发表回答