Bob
Bob

Reputation: 1211

Multiple touches on UIButton with Swift?

I am trying to count the number of fingers someone touches the button with at the same time.

I tap one time: +1, I tap with two fingers: +2, I tap with three fingers: +3 and so on...

What I currently have:

var count = 0;
@IBAction func onTap(sender: UIButton) {
    count++;
}

The "onTap" function however, fires only one time even if I touch the button with multiple fingers.

How would I track the number of fingers the button has been touched with?

Upvotes: 0

Views: 2125

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236260

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var bigButton: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        let oneFingerTap = UITapGestureRecognizer(target: self, action:"oneFingerTapDetected:")
        oneFingerTap.numberOfTouchesRequired = 1
        let twoFingerTap = UITapGestureRecognizer(target: self, action:"twoFingerTapDetected:")
        twoFingerTap.numberOfTouchesRequired = 2
        let threeFingerTap = UITapGestureRecognizer(target: self, action:"threeFingerTapDetected:")
        threeFingerTap.numberOfTouchesRequired = 3
        bigButton.addGestureRecognizer(oneFingerTap)
        bigButton.addGestureRecognizer(twoFingerTap)
        bigButton.addGestureRecognizer(threeFingerTap)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    func oneFingerTapDetected(sender:UITapGestureRecognizer) {
        println("one")
    }
    func twoFingerTapDetected(sender:UITapGestureRecognizer) {
        println("two")
    }
    func threeFingerTapDetected(sender:UITapGestureRecognizer) {
        println("three")
    }
}

Upvotes: 2

Related Questions