SwiftUI无法将按钮与topLeading对齐

时间:2020-04-02 06:24:35

标签: swift swiftui

我有一个button,无法与topLeading对齐到左上方。 我希望完成的任务:

What I want

我的代码:

var body: some View {
        ZStack {
            ZStack(alignment: .topLeading) {
                Button(action: { self.show.toggle() }) {
                    HStack {
                        Spacer()
                        Image(systemName: "list.dash")
                            .foregroundColor(.black)
                    }
                    .padding(.trailing, 20)
                    .frame(width: 90, height: 60)
                    .background(Color.white)
                    .cornerRadius(30)
                    .shadow(color: Color("buttonShadow"), radius: 10, x: 0, y: 10)
                }
                Spacer()
            }

        }
    }

但是我明白了:

My work

2 个答案:

答案 0 :(得分:1)

添加背景空间使用方,如下所示(已通过Xcode 11.4测试)

demo

ZStack(alignment: .topLeading) {
    Color.clear                               // << here !!
    Button(action: { self.show.toggle() }) {

答案 1 :(得分:1)

问题在于,默认情况下,您的换行视图(两个ZStack)将仅占据其内容的空间,即按钮。如果添加框架以允许包装器展开,则会看到对齐方式按预期工作。

var body: some View {
    ZStack {
        ZStack {
            Button(action: { self.show.toggle() }) {
                HStack {
                    Spacer()
                    Image(systemName: "list.dash")
                        .foregroundColor(.black)
                }
                .padding(.trailing, 20)
                .frame(width: 90, height: 60)
                .background(Color.white)
                .cornerRadius(30)
                .shadow(color: Color.gray, radius: 10, x: 0, y: 10)
            }
            Spacer()
        }
        .frame(
            maxWidth: .infinity,
            maxHeight: .infinity,
            alignment: Alignment.topLeading
        )
    }
}

Screenshot of correct behavior