1.当设备摇动时,系统会算出加速计的值,并告知是否发生了摇动手势。系统只会运动开始和结束时通知你,并不会在运动发生的整个过程中始终向你报告每一次运动。例如,你快速摇动设备三次,那只会收到一个摇动事件。
2,想要实现摇动手势,首先需要使视图控制器成为第一响应者,注意不是单独的控件。成为第一响应者最恰当的时机是在视图出现的时候,而在视图消失的时候释放第一响应者。
-(BOOL)canBecomeFirstResponder
{
return YES;
} -(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self becomeFirstResponder];
} -(void)viewWillDisappear:(BOOL)animated
{
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
现在,视图控制器准备处理运动事件,其中有三个方法,motionBegan,motionEnded和motionCancelled,这些与触摸方法有着相似的工作原理,但没有移动方法。
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.type == UIEventSubtypeMotionShake)
{
NSLog(@"Shake Began");
}
} -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.type == UIEventSubtypeMotionShake)
{
NSLog(@"Shake End");
}
} -(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.type == UIEventSubtypeMotionShake)
{
NSLog(@"Shake Cancelled");
}
}
以上是转载自http://blog.csdn.net/marvindev
我的代码:
//
// ocqViewController.m
// shake
//
// Created by ocq on 14-4-29.
// Copyright (c) 2014年 ocq. All rights reserved.
// #import "ocqViewController.h" @interface ocqViewController () @end @implementation ocqViewController - (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"初始化了实例");
// Do any additional setup after loading the view, typically from a nib.
} - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} -(BOOL)canBecomeFirstResponder
{
return YES;
} -(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self becomeFirstResponder];
} -(void)viewWillDisappear:(BOOL)animated
{
[self resignFirstResponder];
[super viewWillDisappear:animated];
} ////当手机移动结束时调用该方法
#pragma motion移动的类型 UIEvent事件
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{ //如果是摇手机类型的事件
if(motion==UIEventSubtypeMotionShake){
NSLog(@"摇动了手机");
//创建并初始化对话框 UIAlertView *show=[[UIAlertView alloc] initWithTitle:@"ocq ios 学习" message:@"恭喜,您查找到了好友" delegate:nil cancelButtonTitle:@"添加为好友" otherButtonTitles: nil]; //显示对话框 [show show]; // [show release];
}
}
@end