add hyphens on word break in a UILabel

David Ben Ari picture David Ben Ari · Sep 24, 2013 · Viewed 12.6k times · Source

How do I set a UILabel lineBreakMode to break words and add hyphens to broken words?

a label with a broken wo-

rd should look like this

Answer

Kenny Winker picture Kenny Winker · Oct 16, 2013

Elaborating on Matt's answer here: https://stackoverflow.com/a/16502598/196358 it can be done using NSAttributedString and NSParagraphStyle. See below:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.hyphenationFactor = 1.0f;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleString attributes:@{ NSParagraphStyleAttributeName : paragraphStyle }];

self.titleLabel.attributedText = attributedString;

This will cause the label to break at logical places mid-word using hyphens. It looks great, and is pretty simple to do. It requires iOS 6.0, but I've only tried it under 7.0.