是否可以禁用一半的步进器

Is it possible to disable half of the Stepper

我想在步进器值为零时禁用一半步进器。

我在步进器上尝试了 .disabled 函数,但它禁用了整个步进器,我只想禁用步进器的递减部分。

struct StepperLabelView : View {
    @ObservedObject var social: Social

    var body: some View {
        VStack {
            Stepper(onIncrement: {
                self.social.quantity += 1
                socialsInCanvas += [Social(companyName: self.social.companyName)]
            }, onDecrement: {
                self.social.quantity -= 1
                socialsInCanvas.removeLast()
            }, label: { Text("") })
                .disabled(social.quantity == 0)
        }
        .padding()
    }
}

您可以将您的 onDecrement 代码包装在一个条件中,或者使用两个按钮滚动您自己的代码。

        HStack {
            Button(
                action: { self.item += "+" },
                label: { Image(systemName: "plus.circle") }
            )
            Text(item)
            Button(
                action: { self.item += "-" },
                label: { Image(systemName: "minus.circle") }
            )
        }

只需在适当的时候禁用“-”按钮即可。 plus.square 可能是更好的符号,https://sfsymbols.com 是比较它们的好地方。

Stepper 可以取范围来激活每个按钮:

struct ContentView : View {

    @State var quantity = 3

    var body: some View {
        VStack {
            Stepper("Count: \(quantity)", value: $quantity, in: 0...Int.max)
        }
        .padding()
    }
}

您可以使用 onEditingChanged 参数来添加额外的工作。 你也可以观察 quantity:

@State var quantity = 3 {
    didSet {
        if oldValue < quantity {
            // Probably + button touched
            return
        }

        if oldValue > quantity {
            // Probably - button touched
            return
        }

        if oldValue == quantity {
            // Unknown
        }

    }
}