Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Text justified alignment

Has anyone found a way to align the string in a Text in a justified way?

In my reading app I'd like to offer the user to choose the justified alignment, where both the .leading both the .trailing alignments are true at the same time. Unfortunately the .multilineTextAlignment modifier for the Text has only three options: .leading, .center and .trailing.

If not I can still wrap an UILabel into a UIViewRepresentable since the UILabel has the .justified alignment option, but I thought it should be available in the Text as well and I was not able to find it.

like image 822
hastoro11 Avatar asked Oct 16 '22 06:10

hastoro11


1 Answers

I know I'm late but I faced same issue , I will write it here, it could help other developer in future

Unfortunately until now Apple doesn't suppourt .justified in SwiftUI 2.0

you need to depend on UIKit

Add this code in your project

   struct LabelAlignment: UIViewRepresentable {
    var text: String
    var textAlignmentStyle : TextAlignmentStyle
    var width: CGFloat

    func makeUIView(context: Context) -> UILabel {
        let label = UILabel()
        label.textAlignment = NSTextAlignment(rawValue: textAlignmentStyle.rawValue)!
        label.numberOfLines = 0
        label.preferredMaxLayoutWidth = width
        label.setContentHuggingPriority(.required, for: .horizontal)
        label.setContentHuggingPriority(.required, for: .vertical)

        return label
    }

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

enum TextAlignmentStyle : Int{
     case left = 0 ,center = 1 , right = 2 ,justified = 3 ,natural = 4
}

Then use it like this

LabelAlignment(text: "Your text here", textAlignmentStyle: .justified, width: UIScreen.main.bounds.width - 20)

change 20 to any number you like to add space on left and right

my solution will will depend on text content size if the text is small the view will be small and vice versa so it will act as Text()

like image 132
Basil Avatar answered Oct 19 '22 02:10

Basil