Simple implementation.
There are several monitoring responses in the uiresponder class.
Responding to touch events
-Touchesbegan: withevent:
-Touchesmoved: withevent:
-Touchesended: withevent:
-Touchescancelled: withevent:
Responding to Motion Events
-Motionbegan: withevent:
-Motionended: withevent:
-Motioncancelled: withevent:
-Motionended: withevent:
The parameter event is available
Typedef Enum {
Uieventsubtypenone = 0,
Uieventsubtypemotionshake = 1,
Uieventsubtyperemotecontrolplay = 100,
Uieventsubtyperemotecontrolpause = 101,
Uieventsubtyperemotecontrolstop = 102,
Uieventsubtyperemotecontroltoggleplaypause = 103,
Uieventsubtyperemotecontrolnexttrack = 104,
Uieventsubtyperemotecontrolprevioustrack= 105,
Uieventsubtyperemotecontrolbeginseekingbackward = 106,
Uieventsubtyperemotecontrolendseekingbackward = 107,
Uieventsubtyperemotecontrolbeginseekingforward = 108,
Uieventsubtyperemotecontrolendseekingforward = 109,
} Uieventsubtype;
What we use to determine shake is uieventsubtypemotionshake.
See the code below.
// Shakewindow. h
# Import <uikit/uikit. h>
@ Interface shakewindow: uiview
@ End
// Shakewindow. m
# Import "shakewindow. H"
@ Implementation shakewindow
-(ID) initwithframe :( cgrect) Frame
{
Self = [Super initwithframe: frame];
If (Self ){
// Initialization code
}
Return self;
}
/*
// Only override drawrect: If you perform custom drawing.
// An empty implementation adversely affects performance during animation.
-(Void) drawrect :( cgrect) rect
{
// Drawing code
}
*/
-(Void) motionbegan :( uieventsubtype) motion withevent :( uievent *) event
{
}
-(Void) motionended :( uieventsubtype) motion withevent :( uievent *) event
{
If (motion = uieventsubtypemotionshake)
{
// User was shaking the device. Post a notification named "Shake ".
[[Nsicationcenter center defacenter center] postnotificationname: @ "Shake" Object: Self];
}
}
-(Void) motioncancelled :( uieventsubtype) motion withevent :( uievent *) event
{
}
@ End
Add and use this wiindow elsewhere, and then monitor the implementation:
........
{
// Add the shake noticefication.
[[Nsicationcenter center defacenter center] addobserver: Self selector: @ selector (shakeme) Name: @ "Shake" Object: Nil];
......
}
-(Void) shakeme
{
Uialertview * alertview = [[uialertview alloc] initwithtitle: @ "bing" message: @ "Shake me" delegate: Nil cancelbuttontitle: @ "OK" otherbuttontitles: nil, nil]
[Alertview show];
}
That's over.