Search code examples
iosswiftuibuttonviewdidload

Swift: Getting a Button to work


I created two buttons in my viewDidLoad() function:

    buttonZ.frame = CGRectMake(0, 20, 100, 50)
    buttonZ.backgroundColor = UIColor.greenColor()
    buttonZ.setTitle("Zurück", forState: UIControlState.Normal)
    buttonZ.addTarget(self, action: "buttonZAction:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(buttonZ)

    buttonV.frame = CGRectMake(screenBreite - 100, 20, 100, 50)
    buttonV.backgroundColor = UIColor.greenColor()
    buttonV.setTitle("Vorwärts", forState: UIControlState.Normal)
    buttonV.addTarget(self, action: "buttonVAction:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(buttonV)

Outside the viewDidLoad() I implemented the two functions buttonZAction()and buttonVAction()

    func buttonZAction(){
    if(level - 1 >= 1){
        level = level - 1
        spielfeldChooser()
    }
}

func buttonVAction(){
    if(level + 1 <= maxLevel){
        level = level + 1
        spielfeldChooser()
    }
}

The problem appears when I am hitting on of these buttons. An exception appears somewhere, which I do not catch (I just included the main part of the error).

`*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Pushy_2_0.ViewController buttonVAction:]: unrecognized selector sent to instance 0x15db5410'

I hope You can help me.


Solution

  • You have "buttonZAction:" it means that your selector should receive a parameter. If you don't pass them change these lines:

    buttonZ.addTarget(self, action: "buttonZAction:", forControlEvents: UIControlEvents.TouchUpInside)
    buttonV.addTarget(self, action: "buttonVAction:", forControlEvents: UIControlEvents.TouchUpInside)
    

    To:

    buttonZ.addTarget(self, action: "buttonZAction", forControlEvents: UIControlEvents.TouchUpInside)
    buttonV.addTarget(self, action: "buttonVAction", forControlEvents: UIControlEvents.TouchUpInside)