ppalancica
ppalancica

Reputation: 4277

Overriding touchesBegan in Swift

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!

Upvotes: 2

Views: 3247

Answers (1)

Rob
Rob

Reputation: 437907

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)
        ...
    }
}

Upvotes: 4

Related Questions