Reading time: 1 min

This recipe shows how to render justified text in SwiftUI.

The end result looks like this:

preview

Unfortunately, SwiftUI doesn't support justifying text natively. The TextAlignment enum doesn't contain this option, forcing us to resort to good old UIViewRepresentable to make it happen:

struct JustifiedText: UIViewRepresentable {
  private let text: String
  private let font: UIFont

  init(_ text: String, font: UIFont = .systemFont(ofSize: 18)) {
    self.text = text
    self.font = font
  }

  func makeUIView(context: Context) -> UITextView {
    let textView = UITextView()
    textView.font = font
    textView.textAlignment = .justified
    return textView
  }

  func updateUIView(_ uiView: UITextView, context: Context) {
    uiView.text = text
  }
}

Then, you can use it like this:

JustifiedText("This is some really, really, really long text so showcase how show justified text in SwiftUI, spanning over multiple lines. Unfortunately, this doesn't work with regular Text view, nor does it work with AttributedString.")
What doesn't work - Text with AttributedString

NSAttributedString has the option to justify its content via the paragraphStyle key. Since, as of SwiftUI 3, Text views natively support attributed strings, one would expect that you can use the same code to get native justify support in SwiftUI, right?

var paragraphStyle: NSParagraphStyle {
  let style = NSMutableParagraphStyle()
  style.alignment = .justified
  return style
}

var body: some View {
  Text(AttributedString(
    "This is some really, really, really long text so showcase how show justified text in SwiftUI, spanning over multiple lines. Unfortunately, this doesn't work with regular Text view, nor does it work with AttributedString.", 
    attributes: AttributeContainer([.paragraphStyle: paragraphStyle])))

Except it just doesn't work:

Screenshot%202021-10-22%20at%2012.51.54

Hopefully this changes soon and we get native support for justified text in

Next Post Previous Post