iPhone can detect motion events whenever the user shakes, moves, or tilts their device. iPhone has built-in hardware called an accelerometer and a gyroscope, which detect these types of events and pass the information back to your code.
Let's start with the shake event. When you want to detect a shake, you will need to designate your object as the first responder. To become the first responder, you will need to add the following code to your object:
-(BOOL)canBecomeFirstResponder { return YES; } -(void) viewDidAppear:(BOOL)animated { [self becomeFirstResponder]; }
Once you have your responder set up, you need to add a method to handle the event. There are three motion methods that you can use: motionEnded:withEvent:
, motionEnded:withEvent:
, and motionEnded:withEvent:
. These are similar to the touch events we talked about earlier. To detect the shake, you will need to check UIEventSubType
that is sent in with the method:
-(void)motionEnded:(UIEventSubtype...