2

I'm trying to get the coordinates of a touch on the screen, but every time it just gives me 0, 0. I could only find basic help with this function in the new version of Swift, and nothing on this problem. What am I doing wrong here?

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        let touch = touches.first as! UITouch
        let location = touch.locationInView(self.view)
        NSLog("location: %d, %d", location.x, location.y)
}

Thanks!

noizybrain
  • 155
  • 1
  • 15
  • 1
    The coordinates are CGFloats and must be printed with "%f". Does the compiler not show a warning? – Martin R Apr 30 '15 at 21:30
  • Derp. Thanks, Martin, that was it! There was no warning. – noizybrain Apr 30 '15 at 21:34
  • 1
    I know the question has already been answered. I just would like to encourage you to use println instead of NSLog. The println function is the Swift way to print values and it is much easier and essential then NSLog because you don't need the format specifiers. **println("location \\(location)")** – Luca Angeletti Apr 30 '15 at 22:15

1 Answers1

3

As per swift 1.2

override func touchesEnded(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    if let touch = touches.first as? UITouch {
        let location = touch.locationInView(self.view)
        println("Location: \(location)")
    }
}

As per swift 1.1

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        let touch = touches.anyObject() as? UITouch
        let location = touch?.locationInView(self.view)
        println("Location: \(location)")
    }

Tested.

iamktothed
  • 1,398
  • 2
  • 14
  • 22
Ruchish Shah
  • 319
  • 1
  • 6