This post deals with detecting shakes in an iPhone application. The shake API has 3 events which can be handled in your code
a) motionBegan:
b) motionEnded:
c) motionCancelled:
Now lets see how you can code these events in your application
1)Open Xcode, make a view based application and name it as shake.
2)Open shakeViewController.xib and populate it with a TextField and a UIDatePicker as shown below
3) Now open shakeViewController.h file. Add the following highlighted code
#import <UIKit/UIKit.h>
@interface ShakeViewController : UIViewController {
IBOutlet UITextField *textField;
IBOutlet UIDatePicker *datePicker;
}
@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, retain) UIDatePicker *datePicker;
-(IBAction) doneEditing: (id) sender;
@end
4) In the Interface Builder make the connections for textField and datePicker
5) Right click the textField and connect its Did End On Exit event to doneEditing: method as shown below
6) Now write the following highlighted code in the shakeViewController.m file
#import "ShakeViewController.h" @implementation ShakeViewController @synthesize textField, datePicker; -(void) viewDidAppear:(BOOL)animated { [self.view becomeFirstResponder]; [super viewDidAppear:animated]; } -(IBAction) doneEditing: (id) sender { [self.view becomeFirstResponder]; } -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (event.subtype == UIEventSubtypeMotionShake ) { NSLog(@"motionBegan:"); } } -(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (event.subtype == UIEventSubtypeMotionShake ) { NSLog(@"motionCancelled:"); } } -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (event.subtype == UIEventSubtypeMotionShake ) { NSLog(@"motionEnded:"); } } -(void)dealloc { [textField release]; [datePicker release]; [super dealloc]; }
7) Right click the classes group and choose add new file. Select the UIView subclass template.
Name the file as ShakeView.
9) Open ShakeView.m and add the following method
-(BOOL)canBecomeFirstResponder
{
return YES;
}
10) In Interface Builder, select the View window and view its Identity Inspector window. Select its class name as ShakeView.
11) Save everything and then run the application.
12) To simulate shaking on simulator choose Hardware->Shake Gesture
13) Observe the console.
Note: You should have first responder in your view to fire the events. So we have set view to first responder in viewDidAppear: and then again when keyboard is dismissed we make view as first responder in doneEditing: method. By default your view will never be first responder so you will have to override the default canBecomeFirstResponder method to return a YES:









