SwiftUI: Aligning views to the leading & trailing edges of another view in a VStack

orj*_*orj 1 layout alignment ios swiftui

How do you align content to the leading and trailing edges of another view in a SwiftUI VStack?

我目前有以下SwiftUI代码:

struct MyBlock: View {
    var body: some View {
        Rectangle().foregroundColor(.gray).frame(width: 80, height: 80)
    }
}

struct MyGridView: View {
    var body: some View {
        HStack(spacing: 16) {
            MyBlock()
            MyBlock()
            MyBlock()
        }                       
    }
}

struct PinPad: View {
    var body: some View {
        VStack {
            MyGridView()
            HStack {
                Button(action: {}, label: { Text("Left Align") })
                Spacer()
                Button(action: {}, label: { Text("Right Align") })
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果呈现如下:

垫片会消耗所有可用空间

但是我真正想要的是"Left Align" Button与的左/前边缘对齐,MyGridView并且与"Right Align" Button的右/后边缘对齐MyGridView

例如,像这样:

对齐的按钮

我显然在这里遗漏了一些非常基本的东西,因为在UIKit中使用自动布局来做到这一点很简单。

kon*_*iki 8

解决布局问题的第一件事是在视图上添加边框。这将使您看到视图的真实(和不可见)范围。问题将变得更加明显:

在此处输入图片说明

在您的情况下,可以通过将其全部包装在HStack中并添加一些间隔符来轻松修复它:

在此处输入图片说明

struct PinPad: View {
    var body: some View {
        HStack {
            Spacer()
            VStack {
                MyGridView().border(Color.blue, width: 3)
                HStack {
                    Button(action: {}, label: { Text("Left Align") }).border(Color.red, width: 3)
                    Spacer()
                    Button(action: {}, label: { Text("Right Align") }).border(Color.red, width: 3)
                }
            }.border(Color.green, width: 3)
            Spacer()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)