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:
-
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.
-
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 toUIView. They need to be converted to the layer's coordinate system (convert(_, from:)orconvert(_, to:)). - The
hitTest(_:)method works with points in the caller layer's coordinate system (myLayer.hitTest(locationInLayer)). - If the layer is invisible (
alpha = 0orisHidden = true),hitTestreturnsnil.containsreturnstrueif the point is within bounds, ignoring visibility. - For complex layer hierarchies, recursive search or checking the returned
hitLayermay be necessary.