SwiftUI 填充距离不一致

ivy*_*-yw 12 ios swift swiftui

我在 macos 11.2.2 上使用 Xcode 12.4 和 Swift 5.4我想控制两个视图
之间的空间。Text自然而然地padding就想到了。这是代码

VStack(alignment: .leading) {
    Text("Exploring San Francisco")
        .font(.appTitle1)
        .fontWeight(.bold)
        .padding(.bottom, 0)
    Text("May 1, 2021 - May 5, 2021")
        .font(.appSmallBody)
        .fontWeight(.bold)
        .textCase(.uppercase)
        .foregroundColor(.init(hex: "666666"))
}
Run Code Online (Sandbox Code Playgroud)

请注意,我明确写底部填充为 0px。结果如下: 图像底部内边距 0px

现在,如果我想要它们之间有 1px 的填充,填充就会变得太大。这是底部填充 1 像素的结果:
图像底部内边距 1px

正如你可能知道的那样,它们之间的距离绝对不是 1px,而是更像 10px。

但是,如果我将内边距增加到 2px,您几乎看不到 1px 和 2px 之间的差异:
图像底部内边距 2px

为什么填充距离不一致?

我发现的唯一解决方法是删除padding并使用VStack'sspacing参数:

VStack(alignment: .leading, spacing: 1) {
    Text("Exploring San Francisco")
        .font(.appTitle1)
        .fontWeight(.bold)
    Text("May 1, 2021 - May 5, 2021")
        .font(.appSmallBody)
        .fontWeight(.bold)
        .textCase(.uppercase)
        .foregroundColor(.init(hex: "666666"))
}
Run Code Online (Sandbox Code Playgroud)

但是,当堆栈中有多个视图并且我想自定义每对视图之间的距离时,这并不理想。

这是 SwiftUI 的错误吗?对于这个问题有更优雅的解决方法吗?谢谢!

Eli*_*ben 18

您可以尝试执行以下操作:基本上在vstack上声明spacing: 0,然后更改填充,它将按照您想要的方式运行。

    VStack(alignment: .leading, spacing: 0) {
        Text("Exploring San Francisco")
            .font(.title)
            .fontWeight(.bold)
            .lineLimit(1)

        Text("May 1, 2021 - May 5, 2021")
            .font(.subheadline)
            .fontWeight(.bold)
            .textCase(.uppercase)
            .foregroundColor(Color.gray)
            .padding(.top, 1)
    }
Run Code Online (Sandbox Code Playgroud)

更改示例中的最后一行,您可以看到与

.padding(.top, 0)

.填充(.顶部, 1)

.padding(.top, 5)