Graphics Reference
In-Depth Information
the color application example, the window is the first responder. Because we want to
receive and process key events, we first want to make our
LZContentView
accept first
responder status. We do this by overriding the
-acceptsFirstResponder
method, as
shown in Listing 11-14.
LISTING 11-14
LZContentView -acceptsFirstResponder Implementation
- (
BOOL
)acceptsFirstResponder
{
return YES
;
}
Like the
mouseUp
and
mouseDown
events in Listing 11-14, we want to handle key events
within the delegate instead of directly in the view. Therefore, the
-keyUp:
method passes
the event to the delegate, as shown in Listing 11-15.
LISTING 11-15
LZContentView -keyUp: Implementation
- (
void
)keyUp:(
NSEvent
*)theEvent
{
[
delegate keyUp
:theEvent];
}
Back in the
AppDelegate
, we need to give the
contentView
first responder status on start
up so that it can receive key events. To do this, call
[window setFirstResponder:
contentView]
within the
-awakeFromNib
method.
Now that the events are routed to where we want them, it is time to do something with
them. When the
-keyUp:
event is triggered, we want to set the background color based
on the key that was pressed. See Listing 11-16.
LISTING 11-16
Updated AppDelegate -keyUp: Implementation
- (
void
)keyUp:(
NSEvent
*)theEvent
{
CGColorRef
newColor;
if
([[theEvent
charactersIgnoringModifiers
]
isEqualToString
:
@”r”
]) {
newColor =
kRedColor
;
}
else if
([[theEvent
charactersIgnoringModifiers
]
isEqualToString
:
@”g”
]) {
newColor =
kGreenColor
;
}
else if
([[theEvent
charactersIgnoringModifiers
]
isEqualToString
:
@”b”
]) {
newColor =
kBlueColor
;
}
else
{
[
super
keyUp
:theEvent];
return
;
}