Detecting shakes is easy. Balancing the sensitivity so that a lighter shake is required forward and back to trigger an event than sideways, or up and down – that takes a bit more work. Writing this code the first time will make your controller classes look like a mess, so it’s time to refactor that code.
I have written this as a simple class called PLShaker, which you can drop into any app. Â It has one property, a float called ‘violence’, which is a sensitivity scaling parameter, and the default value is 1.5 (more means less sensitive, so it’s not really well named).
To use this class, register to receive a notification from it:
shaker = [[PLShaker alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clear:) name:@"PLShaker.Shake" object:nil];
The @selector should be a method that takes a NSNotification argument (actually, with ObjC this doesn’t matter, but that’s the value that will be passed to you – there’s no user data, so you can’t do a whole lot with it).
For me, most of the time the main use is to clear a form if the device is shaken, which is  a method that doubles up as an action.
Post a Comment