Jack Robson
Jack Robson

Reputation: 2302

How to connect UIButton to action using only interface builder

At the moment I am setting up my buttons for my keyboard with the following code:

func setupButtons() {
    for subview in self.view.subviews {
        if subview.isKindOfClass(UIButton) {
            setupButton(subview as! UIButton)
        }
    }
}

func setupButton(btn: UIButton) {
    btn.addTarget(self, action: #selector(KeyboardViewController.keyPressed(_:)), forControlEvents: .TouchUpInside)
}

But is there anyway I can skip this and all the target inside the layout builder so I can save a little bit of time looping through buttons on each keyboard view?

Upvotes: 0

Views: 3124

Answers (2)

TheValyreanGroup
TheValyreanGroup

Reputation: 3599

If you're trying to ask how to do this without coding anything, just go into the assistant editor view of Xcode and Ctrl-drag from your button to the controllers class file. Then when the pop up displays, change outlet to action and give it a method name. This creates the IBAction method for you.

But in reality, the way you are doing it now with the for loop is far better. Especially if you have many buttons.

Upvotes: 0

Frankie
Frankie

Reputation: 11928

Sure, there are two ways to connect objects to Interface Builder, through outlets and actions.

class ViewController: UIViewController {

    @IBOutlet weak var doStuffButton: UIButton!

    @IBAction func doStuff(sender: UIButton) {
        //do stuff
    }
}

After adding that code look in interface builder and click on the view controller for this class.

Click on the connections inspector

Under outlets you will now see doStuffButton, however over the circle to the right of that, press control and click with your mouse, and drag it over to the button you want to connect it to and release. Setting outlets is NOT required for enabling actions. I just wanted to show this to you as well.

In the same pane you will also see received actions and the doStuff: method. Click and drag in the same way and release on the button. Select which type of event you want to process this action (normal is touch up inside).

Once you're all hooked up it should look like this:

enter image description here

There are many other variations of how to do this, but I thought this would get you a quick start.

Upvotes: 2

Related Questions