SwiftUI 如何在表单中居中文本?

tra*_*per 18 swiftui

.multilineTextAlignment(.center)Text里面时似乎没有效果Form,我如何将这个项目居中?

Form {
    Text("I am left aligned")
    Text("Why won't I center?").multilineTextAlignment(.center)
}
Run Code Online (Sandbox Code Playgroud)

tra*_*per 22

这有效。

Form {
    Text("I am left aligned")
    Text("I am centered!")
    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
}
Run Code Online (Sandbox Code Playgroud)


jos*_*zal 13

您可以将文本换行为HStack

Form {
    Text("I am left aligned")
    HStack {
        Spacer()
        Text("I am centered!")
        Spacer()
    }
}
Run Code Online (Sandbox Code Playgroud)


Edw*_*rey 5

用于frame将文本的框架扩展到全宽multilineTextAlignment并使文本(包括换行文本)居中。

Form {
    Text("Centered text, even if wraps")
        .frame(maxWidth: .infinity)
        .multilineTextAlignment(.center)
}
Run Code Online (Sandbox Code Playgroud)