Search code examples
swiftxcodeuistepper

Swift - Xcode How to update stepper depending on a separate variable


I'm struggling with some code and hoping that someone could help me figure out the logic, it sounds quite simple.

I have 2 steppers, stepper1 and stepper2. They both have max values of 10. I have a variable that is the sum of their current values.

I'd like to disable the steppers from increasing in value once they collectively reach 10.

I'm just learning to code so please forgive me if my terminology is incorrect.

This is the code I'm kind working with whilst testing with one of the steppers.

var sumMaxValues = stepper1.value + stepper2.value
var purchaseMax = 10

@IBAction func stepper1Changed(_ sender: UIStepper) {

        if sumMaxValues >= purchaseMax {

            stepper.maximumValue = stepper.value

        }

}

This kind of works but it stops the stepper from being used and only activates the code on click. I'd like to be able to decrease the stepper value so that the steppers can be used again.

So if stepper1 and stepper2 were both 5 (total of 10), then neither would be able to increase, but they could decrease and so change their values again.

I've also attempted to add this to the viewDidLoad() but it's not working. I'm presuming I'm missing a function somewhere or just have the logic all wrong.

Thanks in advance for any advice that you can offer.


Solution

  • You need to create same action method for all steppers and then do the calculation like this way:

    @IBAction func stepperAction(_ sender: UIStepper) {
    
       let calculatedValue = stepper1.value + stepper2.value
    
       stepper1.maximumValue = calculatedValue >= purchaseMax ? stepper1.value: purchaseMax
       stepper2.maximumValue = calculatedValue >= purchaseMax ? stepper2.value: purchaseMax
    }
    

    If you have three steppers then:

    @IBAction func stepperAction(_ sender: UIStepper) {
    
       let calculatedValue = stepper1.value + stepper2.value + stepper3.value
    
       stepper1.maximumValue = calculatedValue >= purchaseMax ? stepper1.value: purchaseMax
       stepper2.maximumValue = calculatedValue >= purchaseMax ? stepper2.value: purchaseMax
       stepper3.maximumValue = calculatedValue >= purchaseMax ? stepper3.value: purchaseMax
    
    }