Gar
Gar

Reputation: 971

Error when adding selector to addTarget function for UIStepper - Swift 3

I am trying to incorporate a UIStepper into a UITextField, while incrementing the value of the stepper, the UITextField updates with it to that value. I keep getting the error:

"Terminating app due to uncaught exception ''NSInvalidArgumentException', reason: '-[Calculator.SplitViewController stepperValueChanged:]: unrecognized selector sent to instance 0x7fd730c0af30"`

Whenever I run my app and tap the "+" button on the stepper.

Any solutions? I checked my selector function and I think it looks right.

override func viewDidLoad() {
    super.viewDidLoad()

    partyOfStepper.autorepeat = true
    partyOfStepper.minimumValue = 1
    partyOfStepper.maximumValue = 99
    partyOfTextField.text = "\(Int(partyOfStepper.value))"
    partyOfStepper.addTarget(self, action: #selector(stepperValueChanged(stepper:)), for: .valueChanged)

}


@IBAction func calculateButtonTapped(_ sender: Any) {
}


func stepperValueChanged(stepper: UIStepper) {

    let stepperMapping: [UIStepper: UITextField] = [partyOfStepper: partyOfTextField]
    stepperMapping[stepper]!.text = "\(Int(stepper.value))"

}

Upvotes: 0

Views: 856

Answers (1)

CoderMike
CoderMike

Reputation: 301

Your code works for me, as Nariv said make sure you haven't previously created an action in the designer for the UIStepper (check in the Connections inspector) :

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var partyOfStepper: UIStepper!
    @IBOutlet weak var partyOfTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        partyOfStepper.autorepeat = true
        partyOfStepper.minimumValue = 1
        partyOfStepper.maximumValue = 99
        partyOfTextField.text = "\(Int(partyOfStepper.value))"
        partyOfStepper.addTarget(self, action: #selector(stepperValueChanged(stepper:)), for: .valueChanged)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func stepperValueChanged(stepper: UIStepper) {

        let stepperMapping: [UIStepper: UITextField] = [partyOfStepper: partyOfTextField]
        stepperMapping[stepper]!.text = "\(Int(stepper.value))"

    }

}

Upvotes: 1

Related Questions