Search code examples
swiftuitext-alignment

SwiftUI: Justify Text


In UIKit there is the option to justify text so that it looks like in a newspaper. However I can not find this option in SwiftUI on Textelement. I only found multiline alignment with .trailing, .leading, .center.

Can someone point me in the right direction?


Solution

  • SwiftUI doesn't yet support justified text, so you'll have to wrap a UIKit view with UIViewRepresentable. So, for justified text, you could wrap UITextView. It would look something like this:

    struct TextView: UIViewRepresentable {
        var text: String
        
        func makeUIView(context: Context) -> UITextView {
            let textView = UITextView()
            textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
            textView.textAlignment = .justified
            return textView
        }
        
        func updateUIView(_ uiView: UITextView, context: Context) {
            uiView.text = text
        }
    }
    

    And from here, you can use it in your views like this:

    struct MyView: View {
        var body: some View {
            TextView(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin quis elementum lorem. Nullam fermentum viverra ipsum a finibus. Vestibulum venenatis risus vel leo sagittis, id aliquet tortor elementum. Aenean elementum orci ac sapien dictum laoreet. Sed placerat, magna sit amet eleifend auctor, odio ligula dapibus lacus, quis interdum ligula velit at est. Curabitur molestie dui sodales faucibus cursus. Duis posuere ex diam, tempor tincidunt nunc venenatis vitae. Integer vulputate odio vitae enim tincidunt, eget vulputate arcu pulvinar. Integer in magna erat.")
            .frame(width: 500, height: 300)
        }
    }