I'm trying to implement the shake "tutorial" on this page, but I think I'm missing something. I copied his accelerometer function into myAppViewController.m file and put some nslogs in there to see if it even gets into the function when I use the simulators "shake" function. Nothing shows up in the debug console.
http://mithin.in/2009/07/28/detecting-a-shake-using-iphone-sdk
Can anyone explain what I might be missing? Or point me to a tutorial?
I found this, which looks promising, but I don't know how to "put it in a UIView"
How do I detect when someone shakes an iPhone?
EDIT - now here's my working code because of the accepted answer's suggestion.
Here's my code to detect the shake gesture in 3.0 iphone sdk.
-(BOOL)canBecomeFirstResponder {
return YES;
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
NSLog(@"{motion ended event ");
if (motion == UIEventSubtypeMotionShake) {
NSLog(@"{shaken state ");
}
else {
NSLog(@"{not shaken state ");
}
}
你绝对不应该听UIAccelerometer
直接与您自己的过滤处理抖动事件。 这是一个高功率运行,只能由那些需要高加速度计采样率的应用程序中使用。 使用新的运动事件,而不是已加入UIEvent
:
http://developer.apple.com/IPhone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/EventHandling/EventHandling.html#//apple_ref/doc/uid/TP40007072-CH9-SW24
就像触摸,运动事件将交付给第一个响应者,再游了响应链,如果第一个响应不响应。 该UIEvent
将有类型UIEventTypeMotion
和亚型UIEventSubtypeMotionShake
。
这是我回答的作品:
//MainViewController.m
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(shake)
name:@"shake" object:nil];
if(event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake)
NSLog(@"motion Began");
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(shake)
name:@"shake"
object:nil];
if(event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake)
NSLog(@"motion Ended");
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(shake)
name:@"shake"
object:nil];
if(event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake)
NSLog(@"motion Cancelled");
}
-(void)viewDidLoad {
[super viewDidLoad];
[self becomeFirstResponder];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[self resignFirstResponder];
}
我只测试与仿真,并返回我:
2010-06-22 12:40:48.799 Cocktails[14589:207] motion Began
2010-06-22 12:40:48.800 Cocktails[14589:207] motion Ended
我希望这种帮助,因为我失去两小时用来这项工作。