如何在VStack Swift UI中居中放置按钮

如何在VStack Swift UI中居中放置按钮,swift,swiftui,Swift,Swiftui,我希望这两个特定元素有不同的对齐方式。标题必须有前导对齐,但另一方面,按钮位于中间。现在我将VStack对齐设置为“领先”。我对Swift用户界面不太熟悉,所以第一个想法是使用多个不同对齐方式的垂直堆栈,但我认为这样做会更容易。如果我将对齐指南添加到按钮,它也不起作用。您可以使用GeometryReader实现以下目的: 容器视图,将其内容定义为其自身大小和坐标空间的函数 我会在下面的演示中使用includedHStack 还有一种方法是使用带有中心对齐和最大宽度的VStack var bo

我希望这两个特定元素有不同的对齐方式。标题必须有前导对齐,但另一方面,按钮位于中间。现在我将VStack对齐设置为“领先”。我对Swift用户界面不太熟悉,所以第一个想法是使用多个不同对齐方式的垂直堆栈,但我认为这样做会更容易。如果我将对齐指南添加到按钮,它也不起作用。

您可以使用
GeometryReader
实现以下目的:

容器视图,将其内容定义为其自身大小和坐标空间的函数


我会在下面的演示中使用included
HStack


还有一种方法是使用带有中心对齐和最大宽度的
VStack

var body: some View {
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        HStack {
            Spacer()
            Button(action: {}){
                Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
            }
            Spacer()
        }
    }.padding(20)
}
Button().frame(宽度:UIScreen.main.bounds.width/2,高度:UIScreen.main.bounds.height/2,对齐:。居中)
GeometryReader { geometry in
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        Button(action: {

        }) {
            Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
                .frame(width: geometry.size.width / 2, height: geometry.size.height / 2, alignment: .center)
        }
    }.padding(20)
}
var body: some View {
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        HStack {
            Spacer()
            Button(action: {}){
                Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
            }
            Spacer()
        }
    }.padding(20)
}
VStack(alignment: .leading) {

        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        VStack(alignment: .center) {
            Button(action: {}){
                Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
            }
        }.frame(maxWidth: .infinity)


    }.padding(20)