Sobes.tech
Middle

How to determine that the user clicked on a layer?

sobes.tech AI

Answer from AI

Use the hitTest: method of UIView, which is embedded in this layer, or check whether the touch point belongs to the layer's frame using the containsPoint: or hitTest: methods.

Example of detecting a touch on a layer inside touchesBegan:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { return }
    let locationInView = touch.location(in: self.view)
    let locationInLayer = self.view.layer.convert(locationInView, to: myLayer) // Convert point to layer coordinates

    if myLayer.contains(locationInLayer) {
        // User touched myLayer
        print("Layer was tapped!")
    }
}