首页 > 解决方案 > SwiftUI:在 Text 之间添加仅 1 的填充会创建一个巨大的填充 - 如何实际制作一个小填充?

问题描述

我有Textsinside VStack,我想在其中添加一些空格。

但是,设置最小可能的填充 (= 1) 会创建一个太大的填充,而填充为零则根本不会创建任何填充。

似乎 SwiftUI 以某种方式计算realPadding = declaredPadding > 0 ? declaredPadding + 8 : 0,这使得更小的填充无法实现。

为什么会这样?这种行为是否真的记录在某处?

现在看来,如果我想拥有例如。文本之间的2pt差距,我不走运。

有没有办法在文本视图之间实际获得比我得到的更小的填充.padding(.bottom, 1)

Nikita Tonsky批评了这种“自动”行为,但他没有想出解决方案。

要粘贴到游乐场的示例代码:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
        var body: some View {
            VStack {
                VStack{
                    Text("Hello World")
                        .background(Color.red)
                        .padding(.bottom, 0)
                    Text("padding 0")
                        .background(Color.red)
                }
                .padding()
                
                VStack{
                    Text("Hello World")
                        .background(Color.red)
                        .padding(.bottom, 1)
                    Text("padding 1 - a huge step-up from 0, why?")
                        .background(Color.red)
                }
                .padding()
                
                VStack{
                    Text("Hello World")
                        .background(Color.red)
                        .padding(.bottom, 2)
                    Text("padding 2 - just 1 pt larger than 1")
                        .background(Color.red)
                }
                .padding()
            }
        }
}

PlaygroundPage.current.setLiveView(ContentView())

它的外观:

SwiftUI 填充错误?

标签: swiftui

解决方案


如果添加(spacing: 0)到 VStack,则填充正好加 1。

VStack(spacing: 0) { // here
    Text("Hello World")
        .background(Color.red)
        .padding(.bottom, 1)
    Text("padding 1 - a huge step-up from 0, why?")
        .background(Color.red)
}
.padding()

在此处输入图像描述


推荐阅读