Among the many properties of the Text
view, I couldn\'t find any related to text alignment. I\'ve seen in a demo that it automatically handles RTL, and when pla
From SwiftUI beta 3 forward, you can center a text view with the frame modifier:
Text("Centered")
.frame(maxWidth: .infinity, alignment: .center)
You can do this via the modifier .multilineTextAlignment(.center)
.
Apple Documentation
We need to align the Text and not the Stack it's in. So calling multilineTextAlignment(.center)
and setting the line limits I can be able to see the texts aligned to center. I don't know why I have to set the line limits, I thought it would expand if you have a large text.
Text("blahblah")
.font(.headline)
.multilineTextAlignment(.center)
.lineLimit(50)
I've actually run into the problem where I had to align text on a single line. What I've found to work is this:
Text("some text")
.frame(alignment: .leading)
If you combine this with the frame width parameter you can get some nice text block formatting for labels and such.
If you would like to keep constant width for the Text, the ".multilineTextAlignment(.leading)" won't take any effect until there is only one line of text.
This is the solution that worked for me:
struct LeftAligned: ViewModifier {
func body(content: Content) -> some View {
HStack {
content
Spacer()
}
}
}
extension View {
func leftAligned() -> some View {
return self.modifier(LeftAligned())
}
}
Usage:
Text("Hello").leftAligned().frame(width: 300)
I'd like to use Spacer()
view to aligning text block.
This example show text at the trailing side:
HStack{
Spacer()
Text("Wishlist")
}