Graphics Reference
In-Depth Information
LISTING 11-16
Continued
if
(
CGColorEqualToColor
([
colorBar backgroundColor
], newColor)) {
newColor =
kBlackColor
;
}
[
colorBar setBackgroundColor
:newColor];
}
We are testing for the three key events in this method:
r
,
g
, and
b
. If the incoming event
does not match any of those three, we abort by passing the event up the chain and
returning out of the method. If it does match, we test against the current background
color of the
colorBar
and either set it or unset it as appropriate.
So far, we have discussed situations in which the entire user interface is built using Core
Animation with a single “root”
NSView
supporting it all. The other equally common situa-
tion is working with layer-backed views as opposed to stand-alone layers.
Unlike the single
NSView
design, layer-backed views are subclasses of
NSResponder
.
Therefore, it is possible to accept mouse and keyboard input at a much lower level.
However, you need to consider a few things when adding user interaction to a layer-
backed view design:
.
Keyboard input
As previously mentioned, because keyboard input does not have an input “point,”
the application needs to keep track of which
NSResponder
receives the key events.
This is done via the responder chain. When developing custom layer-backed
NSView
objects, we need to be aware of the responder chain and handle it appropriately. If
we receive an event and we don't handle it, we need to pass it up the responder
chain so that a potential parent can handle it. If we do not pass the event up, we
can accidentally block things such as keyboard shortcuts to the menus, and so on.
.
Mouse coordinates
Mouse events are easier to handle than keyboard events. When a custom
NSView
receives the mouse event, it is guaranteed to belong to either that
NSView
or one of its
children. However, care does need to be taken to properly translate the coordinates of
that event. As previously discussed in Listing 11-8,
[NSEvent mouseLocation]
returns
the coordinates of the mouse in screen coordinates. Those need to be first translated
to the coordinates of the window and then translated again to the view that received
the event. Because each
NSResponder
has its own internal grid, we need to make sure
we work with the correct coordinates before responding to the click.