swiftswiftui

Is it possible to disable half of the Stepper


I want to disable half of the stepper when the value of the stepper is zero.

I tried the .disabled function on the stepper but it disables the whole stepper and I only want the decrement part of the stepper to be 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()
    }
}

Solution

  • Stepper can take range to activate each button:

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

    You can use onEditingChanged argument for adding extra work. Also you can observe on quantity:

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