TheBlueTurtle
TheBlueTurtle

Reputation: 117

Multiple buttons for one action without IB

In my view controller, I have 10 buttons. Each button has a tag and all the buttons call the same action (separate by a switch (sender.tag), case 0 -> case 9 to differentiate which button is selected). I made with IB, connected all the buttons (@IBOutlet) to the same @IBAction and everything is good. But now I want to do this programmatically, without IB.

So I removed the @IBOutlet's and the @IBAction to create new buttons (let myButton1 = UIBUtton()) and a new action (func newAction(sender: UIButton)). I tried an addTarget: with the same selector for all the new buttons, but the app crashes.

Anyone has an idea to fix it please ?

Upvotes: 2

Views: 2371

Answers (2)

Micro
Micro

Reputation: 10891

Here is what I did. I have two buttons, one on the left and one on the right. I set the tag value to 0 on the left one and 1 on the right one. The enum is all the tags, so you could have as many buttons as you want. Make sure to link the buttons to the same IBAction from storyboard.

class QuestionViewController: UIViewController {

    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var rightButton: UIButton!

    enum ButtonType: Int { case Left = 0, Right }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func questionAnswered(sender: UIButton) {
        switch(ButtonType(rawValue: sender.tag)!){
        case .Left:
            leftButton.setTitle("left button", forState: UIControlState.Normal)
        case .Right:
            rightButton.setTitle("right button", forState: UIControlState.Normal)
        }

    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This should work:

func newAction(sender: UIButton) {
    ...
}
...
myButton1.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside)
myButton2.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside)
myButton3.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside)

Upvotes: 4

Related Questions