Graphics Programs Reference
In-Depth Information
The methods for receiving events are also implemented in
UIResponder
, and they must
be overridden in subclasses of
UIResponder
for instances to respond to events. For
handling shakes, the methods you override in a
UIResponder
subclass are known as
the motion event methods. They are declared like so:
// Send to the first responder when the user starts shaking the device
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
// Sent to the first responder when the user stops shaking the device
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
// Sent to the first responder if the motion event is interrupted, like when
// a phone call or SMS message occurs while shaking
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
Thus, for
HypnosisView
to know and take action when a shake starts, it must imple-
ment the method
motionBegan:withEvent:
. Override this method in
Hypnos-
isView.m
so that the start of a shake changes the
circleColor
.
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"Device started shaking!");
[self setCircleColor:[UIColor redColor]];
}
Build and run the application. Give the device a shake. (If you are using the simulator,
simulate a shake by selecting
Shake Gesture
from the
Hardware
menu in the simulator ap-
plication.) The console reports that the device has started shaking. But no matter how vig-
orously you shake the device, the circle color will not change. What gives?
When the
circleColor
of a
HypnosisView
changes, the instance variable
circleColor
is set to point at a new
UIColor
instance. However, we didn't tell the
HypnosisView
that it needs to redraw its image when this happens. We have to send
the message
setNeedsDisplay
to the
HypnosisView
after it changes its
circleColor
.
In
HypnosisView.m
, implement
setCircleColor:
to send this message after it
changes its
circleColor
instance variable.
- (void)setCircleColor:(UIColor *)clr
{
circleColor = clr;
[self setNeedsDisplay];
}
Build and run the application again. Shake the device, and the circles will change to red.