SwiftUI text-alignment

2019-07-22 21:13发布

问题:

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 placing stuff using View's body, it always centers it automatically.

Is there some concept that I'm missing about layout system in SwiftUI and if not, how can I set the text alignment properties to the Text?

回答1:

I guess SwiftUI wants us to use wrappers like stacks for such things.

So instead of writing something like Text("Hello World").aligned(.leading), the following is encouraged:

VStack(alignment: .leading) {
    Text("Hello World")
}


回答2:

You can set alignment for Vertical stackView as leading. Like below

 VStack(alignment: .leading) {
            Text("Turtle Rock")
                .font(.title)
            Text("Joshua Tree National Park")
                .font(.subheadline)
        }



回答3:

In SwiftUI beta 3, you can center a text view with the frame modifier:

Text("Centered")
    .frame(minWidth: 0, maxWidth: .infinity, alignment: .center)


回答4:

You can do this via the modifier .multilineTextAlignment(.center).

Apple Documentation



回答5:

I was able to get this to align a Text to center:

HStack {
  Spacer()
  Text("Centered")
  Spacer()
}