iosswiftiphonexcodeuistepper

How to divide the value of a number in a "Label" field by the value of a UIStepper?


I am trying writing an app that allows someone to split the tip of a bill. The part I am having difficulty is implementing a UIStepper that will take the value of the "splitTotal" field and divide it by the value of the stepper. Code:

@IBAction func updateTip(_ sender: Any) {
        let tipPercentages = [0.15, 0.20, 0.25]
        
        let bill = Double(billField.text!) ?? 0
        let tip = bill * tipPercentages[tipController.selectedSegmentIndex]
        let total = bill + tip

        let split = total / stepper
        
        tipLabel.text = "$\(tip)"
        totalLabel.text = "$\(total)"
        splitTotal.text = "$\(total)"
        
        tipLabel.text = String(format: "$%.2f",tip)
        totalLabel.text = String(format: "$%.2f",total)
        splitTotal.text = String(format: "$%.2f",split)

Solution

  • When you're using an IBAction to create an action, make sure that you use the proper sender to do so. So the first line of your code should read:

    @IBAction func updateTip(_ sender: UIStepper) {
    

    (Replacing "Any" with "UIStepper") That way, you're inheriting the proper information to perform your calculation.

    Next, instead of typing:

    let split = total / stepper
    

    you can instead do:

    let split = total / sender.value
    

    The sender.value in this case is already a Double, so you shouldn't have a problem performing the rest of the arithmetic.