David Ben Ari David Ben Ari - 3 months ago 31x
iOS Question

add hyphens on word break in a UILabel

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


Elaborating on Matt's answer here: http://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.