Reputation: 601
I'm trying to get shake gesture to work. Here is some code
In my implementation file
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if(event.type == UIEventSubtypeMotionShake)
{
NSLog(@"Shake gesture detected");
}
}
- (BOOL)canBecomeFirstResponder
{
return YES;
}
I read that in order to make shake gesture to work UIView should be the firstResponder. This is why I added that code in implementation
if(self.view.isFirstResponder)
{
NSLog(@"first");
}
else
{
NSLog(@"no");
}
- (void)viewDidAppear {
[self becomeFirstResponder];
}
When I run the app the output of NSLog is NO. What I miss ? And how to get shake gesture to work
Upvotes: 0
Views: 3045
Reputation: 11962
I guess you're doing this in your UIViewController? That's not correct … You have to subclass UIView like this:
ShakeView.h:
//
// ShakeView.h
//
#import <UIKit/UIKit.h>
@interface ShakeView : UIView {
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (BOOL)canBecomeFirstResponder;
@end
ShakeView.m:
//
// ShakeView.m
//
#import "ShakeView.h"
@implementation ShakeView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if ( event.subtype == UIEventSubtypeMotionShake ) {
}
if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] ) {
[super motionEnded:motion withEvent:event];
}
}
- (BOOL)canBecomeFirstResponder
{
return YES;
}
@end
Then use ShakeView instead of your "normal" UIView and implement this in your UIViewController:
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"Shake happend …");
}
- (void)viewDidAppear:(BOOL)animated
{
[self.view becomeFirstResponder];
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self.view resignFirstResponder];
[super viewWillDisappear:animated];
}
That's it. Hope it helps :)
Upvotes: 3