加速度计用于检测设备在x,y和z三个方向上位置的变化.我们可以知道设备相对于地面的当前位置.要测试此示例,您需要在设备上运行它,并且无法在模拟器上运行.
第1步 : 创建一个简单的基于视图的应用程序.
步骤2 : 在 ViewController.xib 中添加三个标签,并创建ibOutlets,将它们命名为xlabel,ylabel和zlabel.
第3步 : 更新ViewController.h如下 :
#import< UIKit/UIKit.h> @interface ViewController:UIViewController< UIAccelerometerDelegate> { IBOutlet UILabel * xlabel; IBOutlet UILabel * ylabel; IBOutlet UILabel * zlabel; } @end
第4步 : 更新 ViewController.m 如下 :
#import"ViewController.h" @interface ViewController() @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[UIAccelerometer sharedAccelerometer] setDelegate:self]; //加载视图后进行任何其他设置,通常来自nib } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; //处理可以重新创建的任何资源. } - (无效)加速度计:(UIAccelerometer *)加速度计didAccelerate: (UIAcceleration *)acceleration { [xlabel setText:[NSString stringWithFormat:@" %F",acceleration.x]]; [ylabel setText:[NSString stringWithFormat:@"%f",acceleration.y]]; [zlabel setText:[NSString stringWithFormat:@"%f",acceleration.z]]; } @end
当我们在中运行应用程序时iPhone 设备,我们将获得以下输出 :