UITextView and NSAttributedString: The Secret of Hyphenation (Swift 4.2.1)


If you want the text within a UITextView to be hyphenated (instead of inappropriately stretched in places when justified), forget NSParagraphStyle and its mutable partner, NSMutableParagraphStyle. At least this is what I've found transforming HTML into attributed text. I can set the hyphenation factor to zero for the paragraph style and the layout manager for the UITextView will override it.

See here an example where a HTML file is held within the Assets folder.
if let asset = NSDataAsset(name: "\(assetName)") {
    let data = asset.data
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.hyphenationFactor = 0.0
    var dict:NSDictionary? = NSDictionary(dictionary: [NSAttributedString.Key.paragraphStyle : paragraphStyle])
    do {
        let attr = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: &dict)
        textView.layoutManager.hyphenationFactor = 0.9
        textView.attributedText = attr
    }
    catch {
        print(error.localizedDescription)
    }
}
Notice that the paragraph style hyphenation factor has purposefully been set to zero (the lowest setting), whereas the layout manager hyphenation setting is at 0.9 (1.0 being the highest).

The paragraph style has no jurisdiction over the layout manager, and every UITextView has a layout manager by default, it's not an optional, even if you've simply added the attributed text to the text view directly and haven't fully employed TextKit (NSTextStorage, NSLayoutManager and NSTextContainer).


Comments