第一种:
第一步:在AppDelegate中设置如下:
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOption s
{
application.applicationSupportsShakeToEdit = YES;
}
第二步:在相应的viewController中添加相应的代码如下:
-(BOOL)canBecomeFirstResponder {
returnYES;
}
-(void)viewDidAppear:(BOOL)animated {
[superviewDidAppear:animated];
[selfbecomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[selfresignFirstResponder];
[superviewWillDisappear:animated];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
if (motion== UIEventSubtypeMotionShake) {
NSLog(@"检测到晃动");
}
}
在模拟器中测试晃动,按组合键:Ctrl + Win + Z
第二种:
利用UIAccelerometer加速器来检测,代码如下:
- (void)viewDidLoad
{
UIAccelerometer *accelerometer = [UIAccelerometersharedAccelerometer];
accelerometer.delegate = self;
accelerometer.undateInterval = 1.0f / 60.0f;
}
- (void)accelerometer:(UIAccelerometer *)accelerometerdidAccelerate:(UIAcceletration *)acceleration
{
if(fabsf(acceleration.x)>2.0||fabsf(acceleration.y>2.0)||fabsf(acceleration.z)>2.0)
{
//NSLog(@"检测到晃动");
}
}