30

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

Top-Master
  • 7,611
  • 5
  • 39
  • 71
David Ben Ari
  • 2,259
  • 3
  • 21
  • 40

6 Answers6

48

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.

WARNING: Font, Color, Alignment --- basically nothing is inherited by attributed-text's render from it's hosting and/or owner UILabel (you need to add those attributes manually).

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Kenny Winker
  • 11,919
  • 7
  • 56
  • 78
  • 3
    I needed a little more. From Apple doc, "hyphenationFactor valid values lie between 0.0 and 1.0 inclusive". I lowered the value to increase the resistance to hyphens. – lorenzo May 06 '14 at 14:15
29

Swift 5.0

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 1.0

let hyphenAttribute = [
    NSAttributedString.Key.paragraphStyle : paragraphStyle,
] as [NSAttributedString.Key : Any]

let attributedString = NSMutableAttributedString(string: "Your String", attributes: hyphenAttribute)
self.yourLabel.attributedText = attributedString

Swift 4.0

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 1.0

let hyphenAttribute = [
    NSAttributedStringKey.paragraphStyle : paragraphStyle,
    ] as [NSAttributedStringKey : Any]

let attributedString = NSMutableAttributedString(string: "Your String", attributes: hyphenAttribute)
self.yourLabel.attributedText = attributedString

Swift 3.0

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 1.0
let attributedString = NSMutableAttributedString(string: “Your String”, attributes: [NSParagraphStyleAttributeName:paragraphStyle])
self.yourLabel.attributedText = attributedString

From Storyboard

enter image description here

XY L
  • 25,431
  • 14
  • 84
  • 143
Krunal
  • 77,632
  • 48
  • 245
  • 261
5

Sometimes it's crucial to add a locale attribute key.

NSString *lorem = @"Lorem ipsum <et cetera>.";

NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.hyphenationFactor = 1;
paragraph.alignment = NSTextAlignmentJustified;
paragraph.lineBreakMode = NSLineBreakByWordWrapping;

self.label.attributedText = [[NSAttributedString alloc] initWithString:lorem attributes:@{
    NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody],
    NSForegroundColorAttributeName: [UIColor darkGrayColor],
    NSParagraphStyleAttributeName: paragraph,
    @"locale": @"la", // Latin, use @"en-US" for American English, for example.
}];
bteapot
  • 1,897
  • 16
  • 24
  • 1
    Is "locale" documented somewhere as a valid attribute name for `NSAttributedString`? There is also an "NSLanguage" attribute, i.e. `kCTLanguageAttributeName`, which is documented in the CoreText header as follows: _Value must be a CFStringRef containing a locale identifier. Default is unset. When this attribute is set to a valid identifier, it will be used to select localized glyphs (if supported by the font) and locale-specific line breaking rules._ – Stephan Tolksdorf Sep 09 '16 at 23:04
  • 1
    I have never tested an `NSLanguage` attribute and never seen any documentation for `@"locale"`, but it definitely works. – bteapot Sep 10 '16 at 04:27
1

I can't delete this as it was accepted, but I am wrong from today's POV.

EARLIER UILabel did not offer Hyphenation.
TODAY it does through NSAttributedString (ios6+)

see: Orthographic hyphenation word in IOS 6.x

Community
  • 1
  • 1
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
0

This will help you. please Change Uilabel Text plain to Attributed enter image description here

Binoy jose
  • 461
  • 4
  • 9
0

Swift 5

class AttributedStrings {
    private func paragraphStyle(alignment: NSTextAlignment, hyphenate: Bool) -> NSMutableParagraphStyle {
        let style = NSMutableParagraphStyle()
        style.hyphenationFactor = hyphenate ? 0.1 : 0
        style.alignment = alignment
        return style
    }
    
    func string(_ string: String, font: UIFont, color: UIColor, alignment: NSTextAlignment = .left, hyphenate: Bool = true) -> NSAttributedString {
        let attributes: [NSAttributedString.Key: Any] = [
            NSAttributedString.Key.font: font,
            NSAttributedString.Key.foregroundColor: color,
            NSAttributedString.Key.paragraphStyle: paragraphStyle(alignment: alignment, hyphenate: hyphenate)
        ]
        return NSAttributedString(string: string, attributes: attributes)
    }
}

let attributedStrings = AttributedStrings()
let attributedString1 = attributedStrings.string("Hyphenate this", font: .boldSystemFont(ofSize: 24), color: .black)
let attributedString2 = attributedStrings.string("Don't hyphenate this", font: .boldSystemFont(ofSize: 24), color: .black, hyphenate: false)
let attributedString3 = attributedStrings.string("Center and hyphenate this", font: .boldSystemFont(ofSize: 24), color: .black, alignment: .center)

let label = UILabel()
label.attributedText = attributedString1

Since we can't subclass NSAttributedString, consider making a vendor class that makes them for you. The key difference with my answer is the hyphenation factor. Hyphenation factor is a float between 0.0 and 1.0. A factor of 1.0 will always hyphenate the word no matter what. A factor of 0.1 will only hyphenate the word if there isn't enough room on the next line to display it without hyphenation. But you can play with the factor to find a threshold that you like.

trndjc
  • 11,654
  • 3
  • 38
  • 51