0

I have researched the other questions related to UIStepper and it seems none answer my specific question (and they're all in Objective C).

Here's my code:

class EditItemViewController: UIViewController {

    @IBOutlet weak var myTextField: UITextField!

    @IBOutlet weak var myStepper: UIStepper!

    @IBAction func stepperChanged(sender: UIStepper) {
        var currentValue = myTextField()!
        let valueFromStepper = Int(sender.value).description
        currentValue += valueFromStepper.toInt()!
        myTextField = currentValue.description
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        myTextField = NSUserDefaults.standardUserDefaults().stringForKey("item")

        myStepper.autorepeat = false

    }

The text field is populated with a value from UserDefaults. The user can change it in the text field or use the stepper. Right now, clicking the + on the stepper properly adds 1 to the text field value. However, pressing again adds 2, then 3, etc. The decrement feature does not work. What am I missing?

Shades
  • 5,568
  • 7
  • 30
  • 48
  • 1
    Learn how to use the *debugger*! Set a breakpoint and inspect the variables. I am sure you'll find your error quickly! – Martin R Mar 26 '15 at 14:11
  • @MartinR As soon as I started reading your comment I realized what I'm doing wrong. Thank you. But what about the decrement feature? – Shades Mar 26 '15 at 14:17

1 Answers1

2

Your logic is incorrect. Each time the stepper value changes, you just add the stepper's current value to your text field. The stepper's value increments or decrements when you press the + or - buttons. You will need to keep track of the stepper's current value, and then compare it when the value changes to see if it has increased or decreased. Then instead of adding the current value to your text field's value, add or subtract 1.

Jasarien
  • 58,279
  • 31
  • 157
  • 188