Get the Location of a Tap

At this point in my iOS studies, I’ve worked with Interface Builder. I have created actions based on a user tapping a label, button or table view cell. All of these capture a tap from the user and use that information to perform an action.

I wanted to know how to capture the point of touch on an interface where there is no button or slider on the view.

I found a simple way to do with by overriding the Touches Began method with this code:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.locationInView(view)

This method is setting a variable, position, as the location of the user touch. When this runs in Xcode, it will print the location of the touch as a a pair of X, Y coordinates to the console. It will look something like this:

(152.0, 521.666656494141)

(225.0, 280.0)

(109.33332824707, 203.666656494141)

(277.666656494141, 497.666656494141)

(135.0, 220.33332824707)

(261.33332824707, 221.33332824707)

Notice the position variable prints as a tuple! Now that we have captured the exact location of a touch on the Interface, we can set other objects to that variable.

One response to “Get the Location of a Tap”

  1. […] From here on out, there are a few different approaches one can take (I’ll link to those I don’t discuss here at the end of the article) but I’ve chosen the workflow that I think lends itself to understanding what’s going on behind the scenes. As colleague Shea Furey-King demonstrates in her post, It’s also a workflow that can be used outside of Sprite Kit for other purposes. […]


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s