Home > OS >  How to remove spacing between label and stepper buttons is SwiftUI Stepper?
How to remove spacing between label and stepper buttons is SwiftUI Stepper?

Time:06-26

It looks like Stepper behaves like a flexible view and tries to take all the width available. I'd like it to shrink to it's minimum width though. Consider the following view:

struct CartListCell: View {
    @State var itemTitle = "Title"
    @State var price = Double.random(in: 1...100)
    @State var quantity = 1
    
    var body: some View {
        HStack(spacing: 10) {
            Image(systemName: "cart")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 40, height: 40)
                .foregroundStyle(Color.yellow, Color.cyan)
            VStack(alignment: .leading, spacing: 5) {
                Text(itemTitle)
                    .font(Font.system(.headline, design: .rounded))
                    .foregroundColor(.primary)
                    .lineLimit(2)
                Text(price, format: .currency(code: Locale.current.currencyCode!))
                    .font(Font.system(.footnote, design: .rounded).weight(.medium))
                    .foregroundColor(.secondary)
            }
            .padding(.horizontal)
            Spacer()
            Stepper("x \(quantity)", value: $quantity, in: 1...50)
        }
    }
}

It produces the following layout where Stepper takes half of the width of HStack.

CartListCell

How can I remove space between "x1" text and stepper buttons?

CodePudding user response:

Just add .fixedSize() to your Stepper and it will shrink to its minimum.

CodePudding user response:

A possible solution is to remove default label and just use external Text, like (tested with Xcode 13.4 / iOS 15.5)

.padding(.horizontal)
Spacer()
Text("x \(quantity)")                     // << here !!
Stepper("", value: $quantity, in: 1...50)
    .labelsHidden()                       // << here !!

demo

  • Related