Ten Eight Studios
SwiftUI Text Alignment

SwiftUI Text Alignment

swift swiftui ios text

Let’s look at the default alignment…

Upon creating a new view, the default Text view takes up as little space as possible and remains centered within the frame. Take a peek at the multi line text view below which shows how the text only takes up as much space as needed.

Default Alignment

Leading edge of textnology!

Little play on words there, if your goal is to align your text with the starting or, leading edge of the frame. There are a few different ways to do so and I personally, tend to find myself putting everything into some sort of stack, whether it is a VStack or an HStack, and using that to align my content accordingly however, I will show you both methods.

When working on aligning horizontally and looking to align all of your content the same, and you’re using an HStack or VStack, you can simply apply the alignment to the stack using VStack(alignment: .leading) or HStack(alignment: .trailing). These two will align all content inside the respective stack types either at the start of the stack or end of the stack, horizontally.

Alternatively, if you just need to align a single text object or need to specify a single text object alignment, you can do so by applying the .frame() modifier and specifying the alignment.

Vertical Alignment

Do you prefer the top or bottom of a cupcake?

I tend to find vertical alignment to be tricky, it’s just me though because it truly is simple. To align things to the top of the vertical axis, it’s very similar to the horizontal. However, it does not work within a stack as you would think and I’ll be making an article about that in the future!

With that being said, you’ll use the .frame() modifier and set the alignment as shown below.

Multi Directional Alignment

Mutli-directional text alignment is possible!

While we can align along the basics of an axis, we also have the option to use multi-directional alignment. This will allow us to align along both axes by using one of the following.


Multi Directional Alignment

Multiline text alignment, when you need to be specific.

If you’re working with a design that requires you to specifically align multi-line text objects, SwiftUI makes it very simple with the use of .multilineTextAlignment() which allows us to pass in one of the modifiers shown above.

In conclusion, SwiftUI makes it simple to align text along various axes with the use of modifiers. We can also align multi-line text objects with the use of a single modifier.