Search code examples
swiftuitouch

How to detect UITouch location visible in Swift 3


I am trying to detect a UITouch event visible.When touch event begins.Currently, I am using below code to detect the touch location.From below code,I can able to print the touch location.Any,help would be greatly appreciated.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
    if let touch = touches.first {
        let position :CGPoint = touch.location(in: view)
        print(position.x)
        print(position.y)
    }
}

Note: I am not trying to draw a line or anything like a drawing app.I,Just want to see the touch event visibly.When happens.

Thanks in advance.


Solution

  • If you want a circle or something to appear when the user taps the screen, try this:

    var touchIndicators: [UIView] = []
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: view)
            let touchIndicator = UIView(frame: CGRect(x: location.x - 10, y: location.y - 10, width: 20, height: 20))
            touchIndicator.alpha = 0.5
            touchIndicator.backgroundColor = UIColor.red
            touchIndicator.layer.cornerRadius = 10
            self.view.addSubview(touchIndicator)
            touchIndicators.append(touchIndicator)
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for indicator in touchIndicators {
            indicator.removeFromSuperview()
        }
        touchIndicators = []
    }
    

    Pretty straightforward. Add circular views when the user touches the screen and remove them when the user lifts his/her fingers. You can also do this using UITapGestureRecognizer.