Home > Software design >  increment/decrement the value of a label with two buttons
increment/decrement the value of a label with two buttons

Time:05-11

being new of swift means that I have issues with two buttons to increment the value of a label.I'm stuck because the increment button works but the decrement button doesn't. the value that I want to store inside the label decrease but the label doesn't update. here's the code, thank you PS: all those isEnabled = true or false are only to disable the buttons to be able create a range from 0 to 5

class ViewController: UIViewController {
var incDec = 0;
@IBOutlet weak var countLbl: UILabel!
@IBOutlet weak var decBtn: UIButton!
@IBOutlet weak var incBtn: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    
    
}
@IBAction func tapDec(_ sender: Any) {
    if(incDec >= -1){
            incDec -= 1;
            self.countLbl.text = "\(incDec)"
            decBtn.isEnabled = true
        }
        else{
            self.countLbl.text = "\(incDec)"
            decBtn.isEnabled = false
            incBtn.isEnabled = true
        }
}


@IBAction func tapInc(_ sender: Any) {

    if(incDecVal < 5){
        incDec  = 1;
        self.countLbl.text = "\(incDec)"
        incBtn.isEnabled = true
    }
    else{
        self.countLbl.text = "\(incDec)"
        incBtn.isEnabled = false
        decBtn.isEnabled = true
    }
    
}

}

CodePudding user response:

You have to modify the logic of enabling and disabling the buttons. Here is the code.

class ViewController: UIViewController {
    var incDecVal = 0;
    @IBOutlet weak var countLbl: UILabel!
    @IBOutlet weak var decBtn: UIButton!
    @IBOutlet weak var incBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        countLbl.text = "\(incDecVal)"
    }

    @IBAction func tapDec(_ sender: Any) {
        if(incDecVal > 0){
            incDecVal = incDecVal - 1;
        }
        
        decBtn.isEnabled = incDecVal == 0 ? false : true
        incBtn.isEnabled = true
        self.countLbl.text = "\(incDecVal)"
    }
    
    @IBAction func tapInc(_ sender: Any) {
        
        if(incDecVal <= 5) {
            incDecVal = incDecVal   1;
        }
        
        incBtn.isEnabled = incDecVal == 5 ? false : true
        decBtn.isEnabled = true
        self.countLbl.text = "\(incDecVal)"
    }
}
  • Related