Accelerometer计用于检测设备在三个方向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];
   //Do any additional setup after loading the view,typically from a nib
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   //处置任何可以重新创建的资源。
}

- (void)accelerometer:(UIAccelerometer *)accelerometer 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 设备上运行应用程序时,将获得以下输出-

iOS Tutorial

参考链接

https://www.learnfk.com/ios/ios-accelerometer.html