Graphics Reference
In-Depth Information
LISTING 11-9
AppDelegate -mouseDown: Implementation
- (
void
)mouseDown:(
NSEvent
*)theEvent;
{
[[
self
buttonLayerHit
]
setSelected
:
YES
];
}
When the
mouseDown
event is received, we want to tell the selected button that it is
selected and have it change its appearance. Because the
-buttonLayerHit
method returns
only
LZButtonLayer
or
nil
, we can safely nest its call within the
-setSelected:
call, as
shown in Listing 11-10.
LISTING 11-10
AppDelegate -mouseUp: Implementation
- (
void
)mouseUp:(
NSEvent
*)theEvent;
{
LZButtonLayer
*hitLayer = [
self
buttonLayerHit
];
[hitLayer
setSelected
:
NO
];
[
colorBar setBackgroundColor
:[hitLayer
myColor
]];
}
Playing with this initial version shows a few issues right away. If the mouse button is
pressed over the
LZButtonLayer
and released while off of it, the button stays selected.
Worse, if one button is pressed and released on another, the second button's color is
selected while the first button stays selected!
To fix these issues, we need to refine the
mouseUp
and
mouseDown
methods, as shown in
Listing 11-11.
LISTING 11-11
Updated AppDelegate -mouseDown: Implementation
- (
void
)mouseDown:(
NSEvent
*)theEvent;
{
LZButtonLayer
*layer = [
self
buttonLayerHit
];
if
(!layer)
return
;
selectedButton
= layer;
[
selectedButton setSelected
:
YES
];
NSRect
buttonRect =
NSRectFromCGRect
([
selectedButton frame
]);
buttonDownTrackingArea
= [[
NSTrackingArea alloc
]
initWithRect
:buttonRect
options
:(
NSTrackingMouseEnteredAndExited
|
NSTrackingActiveInActiveApp
|
NSTrackingEnabledDuringMouseDrag
|
NSTrackingAssumeInside
)
owner
:
self
userInfo
:
nil
];
[[
window contentView
]
addTrackingArea
:
buttonDownTrackingArea
];
}