user4806509
user4806509

Reputation: 3011

Detect two or more UIButtons being pressed at the same time

I have three UIButtons on a storyboard.

What is the most straightforward way to detect when:

or

Upvotes: 1

Views: 1346

Answers (1)

Ghulam Ali
Ghulam Ali

Reputation: 1935

I think it would be easy if you use Touch Down Event and Touch Up Event.

Touch Down: When the finger is pressed

Touch Up: When the finger is lifted.

So on Touch Down set the variable that that specific button is touched and on the Touch Up Event check whether both the Buttons are currently being Touched. Like this:

class ViewController: UIViewController {
    var Button_1_Pressed: Int = 0;
    var Button_2_Pressed: Int = 0;

    @IBAction func Button_1_Down(sender: AnyObject) {
        Button_1_Pressed = 1;
    }

    @IBAction func Button_2_Down(sender: AnyObject) {
        Button_2_Pressed = 1;
    }

    @IBAction func Button_1_Up(sender: AnyObject) {
        if (Button_1_Pressed == 1 && Button_2_Pressed == 1){
            println("1- Both Pressed at same time");
        }
        Button_1_Pressed = 0;
    }

    @IBAction func Button_2_Up(sender: AnyObject) {
        if (Button_1_Pressed == 1 && Button_2_Pressed == 1){
            println("2- Both Pressed at same time");
        }
        Button_2_Pressed = 0;
    }
}

You can set these @IBAction using your XCode interface builder by pressing CTRL key on button and then selecting the event and drag to your swift file. The above code only implements 2 buttons but it would give you an idea for the rest of buttons.

If you are using iOS Simulator you can detect two touches using Option key.

Upvotes: 2

Related Questions