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

狂风中的少年 提交于 2019-12-04 23:21:58

问题


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:

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:


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.



来源:https://stackoverflow.com/questions/30300323/justify-text-in-ios-swift-or-objective-c-without-breaking-tracking-kerning-let

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!