2

I am overriding:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent)

in Swift.

I am wondering, is this correct for getting one touch point:

var touchPoint: CGPoint! = event.touchesForView(self)?.anyObject()?.locationInView(self)

Thanks in advance!

ppalancica
  • 4,236
  • 4
  • 27
  • 42

1 Answers1

4

As of iOS 8.3, touchesBegan takes a touches parameter which is a Set<NSObject>. It's now Set<UITouch>. So, you would:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: view) else { return }

    // use `point` here
}

In previous iOS versions, touchesBegan was defined as a NSSet parameter, as outlined in the question, so you would:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        let touchPoint = touch.locationInView(view)
        ...
    }
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • This no longer compiles, the following post is more up to date and explains the best way of implementing touchesBegan: http://stackoverflow.com/questions/28771896/overriding-method-with-selector-touchesbeganwithevent-has-incompatible-type – Clarkeye May 02 '15 at 13:01
  • The question obviously predated iOS 8.3 and explicitly specified the `NSSet` parameter used in earlier iOS versions, but for the sake of future readers, I've updated it accordingly. Thanks. – Rob May 02 '15 at 13:31