SwiftUI: Adding padding of just 1 between Text creates a huge padding - how to actually make a small padding?

Viewed 342

I have Texts inside VStack, between which I would like to add a bit of whitespace.

However, setting a minimal possible padding (= 1) creates a padding that is too huge, while padding of zero creates no padding at all.

It seems that SwiftUI somehow computes realPadding = declaredPadding > 0 ? declaredPadding + 8 : 0, which makes smaller padding unachievable.

Why is this happening? Is this behaviour actually documented somewhere?

Right now it seems that if I want to have eg. 2pt gap between texts, I'm out of luck.

Is there a way to actually get a padding between Text views smaller than what I get with .padding(.bottom, 1)?

Nikita Tonsky criticizes this "automagic" behavior, but he didn't come up with solution.

Sample code to be pasted into a playground:

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())

How it looks:

SwiftUI padding bug?

1 Answers

If you add (spacing: 0) to VStack, padding is added by exactly 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()

enter image description here

Related