2

I have button and method

 switchViewButton = UIButton.buttonWithType(.System) as? UIButton
    switchViewButton!.frame = CGRectMake(15, 25, 50, 50)
    switchViewButton!.setTitle("sss", forState: .Normal)
    switchViewButton!.addTarget(self, action: "switchViewFunc", forControlEvents: .TouchUpInside)
    switchViewButton!.backgroundColor = UIColor.redColor()
    switchViewButton!.layer.cornerRadius = 25
    topView.addSubview(switchViewButton)


@IBAction func switchViewFunc(sender : AnyObject){
     println("Button was clicked", sender)}

This method crashes app with reason "unrecognized selector sent to instance"

I have another button and method just like this, and it's work perfect. If I'm delete (sender : AnyObject) it works. I cann't understand what is wrong

Ivan R
  • 1,923
  • 5
  • 18
  • 15
  • 1
    Why are you using an IBAction when you're adding it as a target manually? IBAction is specifically for hooking things in IB. You could just define this as a regular function. – Tim Jun 15 '14 at 10:27

3 Answers3

4

Add action this way (pay attention to ":"

switchViewButton!.addTarget(self, action: "switchViewFunc:", forControlEvents: .TouchUpInside)
nerowolfe
  • 4,787
  • 3
  • 20
  • 19
  • It's to strange, I have another button with code lockButton!.addTarget(self, action: "lockandUnlock", forControlEvents: .TouchUpInside) and it's not crashes app – Ivan R Jun 15 '14 at 07:06
  • If you have a parameter in switchViewFunc then you need to add : – nerowolfe Jun 15 '14 at 07:07
  • @IvanR Then that function doesn't have any parameters. You need to understand how method signatures work. See this http://stackoverflow.com/questions/297680/creating-a-selector-from-a-method-name-with-parameters – Mick MacCallum Jun 15 '14 at 07:08
1
@IBAction func switchViewFunc(sender : AnyObject){
     println("Button was clicked", sender)} - ?????

Try this:

func switchViewFunc(sender : UIButton!){
     println("Button was clicked", sender)
}
Anton
  • 3,102
  • 2
  • 28
  • 47
1

@IBAction and an argument are not needed.

func switchViewFunc(){
    println("Button was clicked", sender)
}
mono
  • 4,340
  • 3
  • 21
  • 49