iOS 教程
加速度傳感器是根據(jù)x、y和z三個(gè)方向來檢測在設(shè)備位置的改變。
通過加速度傳感器可以知道當(dāng)前設(shè)備相對于地面的位置。
以下實(shí)例代碼需要在真實(shí)設(shè)備上運(yùn)行,在模擬器上是無法工作的。
1、創(chuàng)建一個(gè)簡單的視圖應(yīng)用程序
2、在ViewController.xib中添加三個(gè)標(biāo)簽,并創(chuàng)建一個(gè)ibOutlets分別為:xlable、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]; // Dispose of any resources that can be recreated. } - (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
當(dāng)我們在iPhone設(shè)備中運(yùn)行該應(yīng)用程序,得到的輸出結(jié)果如下所示。