How to adjust text alignment using multilineTextAlignment()

By | August 13, 2024

Like many other text UI’s SwiftUI’s Text wraps across multiple lines, they align to their leading edge by default. You can change that behavior, by using swiftUI’s ‘multilineTextAlignment()’ modifier to specify an alternative like .center, .trailing etc.

For example, this will center several lines of text as they wrap across lines:

    var body: some View {
        Text("This long string is added here to show you how a long text like this cannot be shown in one line and needs proper alignment to read and look better in screens.")
            .font(.largeTitle)
            .multilineTextAlignment(.center)
            .frame(width: 300)
    }

Let’s use a picker to quickly get the differences between all the varients.

    let alignments: [TextAlignment] = [.leading, .center, .trailing]
     @State private var alignment = TextAlignment.leading

     var body: some View {
         VStack {
             Picker("Text alignment", selection: $alignment) {
                 ForEach(alignments, id: \.self) { alignment in
                     Text(String(describing: alignment))
                 }
             }

             Text("This is an extremely long text string that will never fit even the widest of phones without wrapping")
                 .font(.largeTitle)
                 .multilineTextAlignment(alignment)
                 .frame(width: 300)
         }
     }

There are many other formatting techniques too to explore. Watch this place for more.

Leave a Reply

Your email address will not be published. Required fields are marked *