UITapGestureRecognizer not detecting CALayer in UIScrollView

715 Views Asked by At

I am trying to detect a tap gesture event on CALayers that are a sublayer of a UIScrollView. Here is how I've got the recognizer set up:

In viewDidLoad:

    self.tapRecognizer = UITapGestureRecognizer(target: self, action: "tapHandler:")
    self.tabScroller.addGestureRecognizer(tapRecognizer)

Tap handling method:

 func tapHandler(recognizer: UITapGestureRecognizer) {
    var touchLocation = recognizer.locationInView(recognizer.view)

    if recognizer.state == UIGestureRecognizerState.Ended {

        if let touchedLayer: CALayer = self.tabScroller.layer.hitTest(touchLocation) {
            println("\(touchedLayer.name)")
        }
    }
}

I know that tapHandler is working because it will execute a basic println("") String placed anywhere inside of it.

But println("(touchedLayer.name)") continuously prints nil and I cannot figure out why it is not recognizing a tap above a CALayer.

The CALayers were added to tabScroller using

tabScroller.layer.addSublayer(brushB)

What am I doing wrong?

1

There are 1 best solutions below

0
On

Your CALayer and UIView with the tap are on two different layers of the view hierarchy. Core Animation is lower level than view’s in fact, UIViews are made up of layers. Therefore, you have to use hitTest, or a like function to determine the layer which you are tapping.