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)
            print(position)
        }
}

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 thought on “Get the Location of a Tap

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s