Graphics Reference
In-Depth Information
Hit Test
When a user clicks on an application, two NSEvent objects are generated for that click.
One event is generated when the mouse button is pushed down and a second when the
button is released. To follow this example, applications should also differentiate between
mouseDown and mouseUp events and react accordingly.
When acting on a mouse event, the first
thing we need to do is to determine
which layer is being clicked on. Because
the NSView has an unknown number of
layers in its hierarchy, we cannot assume
which layer is being clicked just by its
location. Fortunately, CALayer has a
-hitTest: method designed to solve
this issue. When CGPoint is passed to
the root CALayer , it returns the deepest
CALayer that the point falls within. This
enables you to quickly determine which
CALayer has been clicked so that your
app can act accordingly.
NOTE
This is an important point to note. Most
events in OS X that we think of as reacting
to a mouse click are actually reacting to
NSEvent 's mouseUp method. For example,
click on a window's Close button and drag
the mouse cursor off the button before
releasing the mouse button. You notice that
the window did not close. This is intended as
a last chance for the user to cancel an
action they did not intend.
Example Application: Color Changer
To demonstrate how the hit test works,
we build a simple application that has
three buttons: Red, Green, and Blue,
along with a color bar that displays the
choice, as shown in Figure 11-1.
The buttons and the color bar are built
using CALayer objects. In the first
version of this application, we deter-
mine which button is clicked on and
respond.
FIGURE 11-1
Color Chooser Example
LZButtonLayer
The first step to building this application is building the buttons. The buttons are
composed of two CALayer objects:
.
The main layer (the LZButtonLayer itself), which handles the border and corner
radius (as shown in Listing 11-3)
.
A CATextLayer object, which display the text (as shown in Listing 11-4)
 
 
 
Search WWH ::




Custom Search