SwiftUI text-alignment

2019-07-22 20:31发布

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?

5条回答
ゆ 、 Hurt°
2楼-- · 2019-07-22 21:11

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

Apple Documentation

查看更多
做个烂人
3楼-- · 2019-07-22 21:14

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

Text("Centered")
    .frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
查看更多
狗以群分
4楼-- · 2019-07-22 21:16

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)
        }

enter image description here

查看更多
别忘想泡老子
5楼-- · 2019-07-22 21:21

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")
}
查看更多
一夜七次
6楼-- · 2019-07-22 21:21

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

HStack {
  Spacer()
  Text("Centered")
  Spacer()
}
查看更多
登录 后发表回答