radex.io

aboutarchiveetsybooksmastodontwitter

WatchKit hyphenation

May 26, 2015
Hey! This is an old post. It reflects my views and the state of the world in 2015, but is likely to be outdated. You’ll find me on Twitter, building Nozbe, and making engineering blueprints.

Quick WatchKit Pro-Tip™ today.

Text on the Apple Watch can be awkward. You probably saw this when developing or using WatchKit apps: huge gaps left by long words wrapped into a new line, and ugly jagged edges in left-aligned blocks of text. Apple deals with this problem in their own apps by hyphenating text on screen. However, WKInterfaceLabel doesn’t support hyphenation… Or that seems to be the common knowledge, anyway.

But it’s actually incorrect. WatchKit does support hyphenation, and it’s very easy.

All you have to do is attribute your text with NSParagraphStyle. This class encapsulates many parameters of text rendering, like leading (line spacing), and hyphenation. Here’s the code:

let style = NSMutableParagraphStyle()
    style.hyphenationFactor = 1

let attributes = [NSParagraphStyleAttributeName: style]
let attributedText = NSAttributedString(string: text, attributes: attributes)
label.setAttributedText(attributedText)

And that’s it! No crazy image rendering needed, just a parameter on your attributed string. Here’s the result:

Unhyphenated and hyphenated WatchKit labels

Most of the time, the difference is rather subtle. But whenever you get a longer word, enabling hyphenation is a huge win.

You can also define a helper method on WKInterfaceLabel to make this even easier:

extension WKInterfaceLabel {
    func setHyphenatedText(text: String) {
        let style = NSMutableParagraphStyle()
            style.hyphenationFactor = 1

        let attributes = [NSParagraphStyleAttributeName: style]
        setAttributedText(NSAttributedString(string: text, attributes: attributes))
    }
}

Boom! That simple.

Published May 26, 2015. Last updated October 05, 2015. Send feedback.