Increment and Decrement Button

I have a label with a minus and plus button beside it. What I want it to do is increment the value of the label by 1 if the plus button is tapped, and subtract 1 if the minus button is tapped.

Accepted Reply

So, + and - are buttons ?


Just create:

- IBOulet for the label : myLabel

    @IBOutlet weak var myLabel: UILabel!


- IBActions for the buttons, such as:


@IBAction func plus() {

    guard let presentValue = Int(myLabel!.text) else { return }

     let newValue = presentValue + 1
     myLabel!.text = String(newValue)
}


idem for minus.

Replies

So, + and - are buttons ?


Just create:

- IBOulet for the label : myLabel

    @IBOutlet weak var myLabel: UILabel!


- IBActions for the buttons, such as:


@IBAction func plus() {

    guard let presentValue = Int(myLabel!.text) else { return }

     let newValue = presentValue + 1
     myLabel!.text = String(newValue)
}


idem for minus.

See this SO thread for an example of stepper functions w/Swift:


https://stackoverflow.com/questions/51657448/plus-and-minus-buttons-for-a-shopping-app-in-swift

How would I get the label so that it can't go below 1?

What are the values you want for label ? Positive and negative ?


You should initially set the label to "0" for instance ; or to any initial value you like.


With this, you can have what you want (connect the "-" button to this :


@IBAction func minus() { 
 
    guard let presentValue = Int(myLabel!.text) else { return } 
 
     let newValue = presentValue - 1 
     myLabel!.text = String(newValue) 
}


Do you use a UIStepper or 2 individual buttons ?


It is even simpler with stepper, but you have to set a maximum and minimum (they can be very very large!)

I am happy to use a stepper how would I connect it to the label or if possible can I display the number between the - and + in the stepper?

Create the stepper in IB.

From the stepper, control-drag to create an IBAction (will be connected to value change)


    @IBOutlet weak var stepperContentLabel: UILabel!     // The label where you want to write

   @IBAction func stepped(_ sender: UIStepper) {     // Connected to the stepper

        stepperContentLabel.text = String(sender.value)
    }

The only thing I want to fix is the fact that right now it displays the numbers as 1.0 I want it to be displayed as 1. How would I do this?

Just replace


   @IBAction func stepped(_ sender: UIStepper) {     // Connected to the stepper 
 
        stepperContentLabel.text = String(Int(sender.value)) 
    }
Hi, I am also working on an app which utilises this, but I need the user's input to be limited to some extent. For example I want the counter to only be able to count from -1 to 20. Could someone point me in the right direction with this? Thanks - I am using roughly the code mentioned here.