Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get coordinates of multiple touches in Swift

So I've been messing around trying to get the coordinates of touches on the screen. So far I can get the coordinates of one touch with this:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject()! as UITouch
    let location = touch.locationInView(self.view)
    println(location)
}

But when touching with two fingers I only get the coordinates of the first touch. Multi-touch works (I tested with this little tutorial: http://www.techotopia.com/index.php/An_Example_Swift_iOS_8_Touch,_Multitouch_and_Tap_Application). So my question is, how do I get the coordinates of the second (and third, fourth...) touch?

like image 217
Fr4nc3sc0NL Avatar asked Feb 24 '15 12:02

Fr4nc3sc0NL


3 Answers

** Updated to Swift 4 and Xcode 9 (8 Oct 2017) **

First of all, remember to enable multi-touch events by setting

self.view.isMultipleTouchEnabled = true

in your UIViewController's code, or using the appropriate storyboard option in Xcode:

xcode screenshot

Otherwise you'll always get a single touch in touchesBegan (see documentation here).

Then, inside touchesBegan, iterate over the set of touches to get their coordinates:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self.view)
        print(location)
    }
}
like image 152
Para Avatar answered Nov 03 '22 17:11

Para


the given touches argument is a set of detected touches. You only see one touch because you select one of the touches with :

touches.anyObject() // Selects a random object (touch) from the set

In order to get all touches iterate the given set

for obj in touches.allObjects {
   let touch = obj as UITouch
   let location = touch.locationInView(self.view)
   println(location)
}
like image 4
giorashc Avatar answered Nov 03 '22 17:11

giorashc


You have to iterate over the different touches. That way you can access every touch.

for touch in touches{
  //Handle touch
  let touchLocation = touch.locationInView(self.view)
}
like image 1
Christian Avatar answered Nov 03 '22 17:11

Christian