Search code examples
iosswiftuiimagetouchuitouch

Assign first user touch to variable


I am trying to enable touch on pieces of a sliding tile puzzle so they can each move around the screen.
I want to assign the user's first tap on the screen to myTouch, then perform some action. In older code, [[touches allObjects] objectAtIndex:0] is what I needed, but not sure how to make this line of code work in Swift.

var tapCen = CGPoint();
var left = CGPoint();
var right = CGPoint();
var top = CGPoint();
var bottom = CGPoint();

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    let allTouches = event?.allTouches()
    let myTouch = allTouches?.first

    if myTouch!.view != self.view
    {
        tapCen = myTouch!.view!.center

    }
}

Solution

  • You can try this

    let allTouches = event.allTouches()
    let myTouch = allTouches?.first
    

    Edit
    Swift 3.0

    let allTouches = event?.allTouches
    let myTouch = allTouches?.first