I've read a number of posts regarding how to开发者_JAVA技巧 detect shakes but I'm not sure:
What is currently the best way to detect shakes?
- and -
How to play an audio file ONLY while the user is shaking the iPhone?
Anyone have an advice, examples/tutorials or sample code?
Thanks
You can implement something like this below in a controller (or any UIResponder actually...). These are available in 3.0 and later. You don't have to go down to the level of the accelerometer if you don't want to do advanced stuff, depends on how much detail you want from the shaking.
- (void)viewDidAppear:(BOOL)animated {
[self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion==UIEventSubtypeMotionShake) {
if ([self paused]) {
[self play];
}
}
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion==UIEventSubtypeMotionShake) {
if ([self playing]) {
[self pause];
}
}
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion==UIEventSubtypeMotionShake) {
if ([self playing]) {
[self pause];
}
}
}
Use the UIAccelerometer and implement the UIAccelerometerDelegate protocol in your class. Perhaps you could do something like this:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acc {
float twoGs = 2.0;
if ((acc.x * acc.x) + (acc.y * acc.y) + (acc.z * acc.z) > twoGs * twoGs) {
if ([self paused]) {
[self play];
}
} else {
if ([self playing]) {
[self pause];
}
}
}
for suitable implementations of the pause, paused, play, playing selectors.
This has been answered before here. I'm using a modified version of the code proposed there, and it works great. Note that in upcoming versions of the OS, you will be able to detect shake gestures through the standard API.
精彩评论