Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 705
netshark1000 Avatar asked Aug 28 '26 15:08

netshark1000


1 Answers

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)
    }
}
like image 90
diogo Avatar answered Aug 31 '26 07:08

diogo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!