swiftuitextfontshyphenation

Enabling automatic hyphenation with custom font size


I recently investigated hyphenation issues in an app I am working on, and built the following simple example:

HStack {
    Text("Gewerberechtsschutzversicherung")
        .font(.body)
        .background(.red)
    Text("Gewerberechtsschutzversicherung")
        .font(.system(size: 17))
        .background(.blue)
}

The result was this: enter image description here

Turns out that setting any sort of custom font size instead of using Apple's predefined enum (.body, .callout etc.) will disable automatic hyphenation of words in SwiftUI.

Is there any way to enable automatic hyphenation in such a scenario? Since the app uses a Styleguide where it retrieves fonts from, using the Apple predefined sizes is not an option here and this disables hyphenation for the entire App. Soft hyphens still work but of course have to be added to every string manually then.


Solution

  • It turns out that adding a soft hyphen anywhere in the string also re-enables automatic hyphenation. So this will use automatic hyphenation on both strings:

    HStack {
        Text("Gewerberechtsschutzversicherung")
            .font(.body)
            .background(.red)
        Text("\u{00AD}Gewerberechtsschutzversicherung")
            .font(.system(size: 17))
            .background(.blue)
    }