如何在SwiftUI Stepper中移除标签和步进按钮之间的间距?

5

看起来 Stepper 表现得像一个灵活的视图,并尝试占用所有可用的宽度。但我希望它可以收缩到最小宽度。 考虑以下视图:

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

它产生了以下布局,其中Stepper占据了HStack一半的宽度。

CartListCell

如何去除"x1"文本和步进按钮之间的空格?

2个回答

8

只需在你的Stepper上添加 .fixedSize(),它就会缩小到最小尺寸。


3
一种解决方案是移除默认标签,只使用外部的 文本,例如 (已在 Xcode 13.4 / iOS 15.5 中测试)。
.padding(.horizontal)
Spacer()
Text("x \(quantity)")                     // << here !!
Stepper("", value: $quantity, in: 1...50)
    .labelsHidden()                       // << here !!

demo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接