Graphics Reference
In-Depth Information
Listing 3.5
Determining the Touched Layer Using
hitTest:
- (
void
)touchesBegan:(
NSSet
*)touches withEvent:(
UIEvent
*)event
{
//get touch position
CGPoint
point = [[touches
anyObject
]
locationInView
:
self
.
view
];
//get touched layer
CALayer
*layer = [
self
.
layerView
.
layer
hitTest
:point];
//get layer using hitTest
if
(layer ==
self
.
blueLayer
)
{
[[[
UIAlertView
alloc
]
initWithTitle
:
@"Inside Blue Layer"
message
:
nil
delegate
:
nil
cancelButtonTitle
:
@"OK"
otherButtonTitles
:
nil
]
show
];
}
else
if
(layer ==
self
.
layerView
.
layer
)
{
[[[
UIAlertView
alloc
]
initWithTitle
:
@"Inside White Layer"
message
:
nil
delegate
:
nil
cancelButtonTitle
:
@"OK"
otherButtonTitles
:
nil
]
show
];
}
}
You should note that when calling a layer's
-hitTest:
method (and this applies to
UIView
touch handling as well, incidentally), the order of testing is based strictly on the
order of layers within the layer tree. The
zPosition
property that we mentioned earlier
can affect the
apparent
order of layers onscreen, but not the order in which touches will be
processed.
That means that if you change the z-order of your layers, you may find you cannot detect
touches on the frontmost layer because it is blocked by another layer that has a lower
zPosition
but is situated earlier in the tree. We explore this problem in more detail in
Chapter 5.