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.
Leave a Reply