7

How can I add hyphenation to a SwiftUI Text? Currently SwiftUI makes a paragraph when there is no space, but this makes everything hard to read and messy.

enter image description here

I have done a bit of research and it seems that there is no native method. Is there another way to achieve this?

J--
  • 172
  • 1
  • 14

1 Answers1

4

A possible approach is to add explicitly "soft hyphen" unicode symbols in places where you want hyphenation.

Here is a demo. Prepared with Xcode 12.4 / iOS 14.4

Case 1: enough space

Text("Minded­­­\u{AD}ness")
    .frame(width: 180)        // << wide frame
    .border(Color.black)

enter image description here

Case 2: limited space

Text("Minded­­­\u{AD}ness")
    .frame(width: 80)        // << limited frame
    .border(Color.black)

demo2

Note: Preview does not understand such unicode symbols, so test on Simulator or real device

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 4
    Not an acceptable solution imo, sorry. With UIKit you can add via attributed strings and `NSMutableParagraphStyle.hyphenationFactor `, must be something similar in swiftUI – Alexandru Motoc May 10 '21 at 16:11
  • Unfortunately this does not seem to work with localization. Any idea how that could be achieved? EDIT: found it - https://stackoverflow.com/questions/29630793/swift-use-unicode-character-in-localization-strings/49689269 – LiMuBei Sep 30 '21 at 10:29