How to get the Touch position on iOS device?


In this post we will be seeing how to get the touch position on device using Swift.

So let’s get started.

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TouchMe”

Step 2 − Open Main.storyboard and add one label as shown below. On this label we will show the touch position.

Step 3 − Create @IBOutlet for the label, name it touchPositionLabel.

Step 4 − We will be overriding the touchesBegan method in ViewController to get the touch position in the view. Override the method as shown below

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
   if let touch = event?.allTouches?.first {
      let loc:CGPoint = touch.location(in: touch.view)
      self.touchPositionLabel.text = " X:\(loc.x) Y:\(loc.y) "
   }
}

The touches began gets called whenever you touch anywhere on the screen. This gives us touch event that contains all the touches.

We are using only the first touch point using event?.allTouches?.first to show the touch location

The ‘event’ is an optional, that’s why we have used if…let binding to unwrap the value.

Then using ‘let loc:CGPoint = touch.location(in: touch.view)’, we are getting the location in touched view.

You will get the touch position in the above method.

Run the project. We are showing the position on the label, that will be seen like below whenever you touch somewhere on the screen.

raja
Published on 11-Sep-2019 12:00:35
Advertisements