Adam Rush

@Adam9Rush

1 March, 2022

Introduction

When you create a new Text view within SwiftUI, you’ll notice its text alignment is leading-edge by default.

struct ContentView: View {
    var body: some View {
        Text("Welcome to SwiftlyRush's bank, you will be able to access your accounts in this application")
            .font(.headline)
            .frame(width: 260)
    }
}

In your above example, you’re creating a new Text view describing our SwiftlyRush bank description, and you’ll notice that by default, it’s aligned to the leading edge.

Using multilineTextAlignment()

SwiftUI has the ability to set the multilineTextAlignment and define the alignment

struct ContentView: View {
    var body: some View {
        Text("Welcome to SwiftlyRush's bank, you will be able to access your accounts in this application")
            .font(.headline)
            .frame(width: 260)
            .multilineTextAlignment(.center)
    }
}

You can see that by setting the .multilineTextAlignment(.center) that the text will now be aligned centrally.

You have three options:

  • .center
  • .trailing
  • .leading

What Next?

It’s that simple, you can now adjust your text alignment, and you’ll notice that we set the frame to 260, allowing you to see the difference visibly. You can, of course, change any of this to suit your requirements.

You can read more about SwiftUI in my various tutorials here.

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.