Sobes.tech
Middle

Kuidas saab määrata, kas kasutaja klõpsas kihil (layer)?

sobes.tech AI

Vastus AI-lt

You can use hit testing: determine which layer was touched. Core Animation provides two methods for this:

  1. hitTest(_:):

    • Checks whether a point is inside the bounds of a layer or any of its sublayers.
    • Returns the deepest sublayer (or the layer itself) containing the point.
    • Considers isHidden = true.
  2. contains(_:):

    • Checks only if the point is within the bounds of the layer itself.
    • Does not consider the hierarchy of sublayers.
    • Does not consider isHidden.

Usually, hitTest is used as it is more accurate for determining interactivity.

Example of using hitTest in a touch handler:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { return }

    let locationInView = touch.location(in: view)

    // Convert point from view coordinates to layer coordinates
    let locationInLayer = myLayer.convert(locationInView, from: view.layer)

    // Perform hit test
    if let hitLayer = myLayer.hitTest(locationInLayer) {
        if hitLayer === myLayer {
            // Touched exactly myLayer
            print("Touched myLayer")
        } else {
            // Touched a sublayer within myLayer
            print("Touched a sublayer within myLayer")
            // Sublayer identification may require additional checks
        }
    } else {
        // Touched outside myLayer and its sublayers
        print("Touched outside myLayer")
    }
}

Important points:

  • The touch point coordinates (location(in:)) are always relative to UIView. They need to be converted to the layer's coordinate system (convert(_, from:) or convert(_, to:)).
  • The hitTest(_:) method works with points in the caller layer's coordinate system (myLayer.hitTest(locationInLayer)).
  • If the layer is invisible (alpha = 0 or isHidden = true), hitTest returns nil. contains returns true if the point is within bounds, ignoring visibility.
  • For complex layer hierarchies, recursive search or checking the returned hitLayer may be necessary.