加速度計沿 X、Y、Z 三個軸向偵測裝置的位置變化,藉此可以判斷目前裝置相對於地面的姿態。
請注意:以下範例必須在真機上執行,模擬器無法提供真實的加速度資料。
1、建立一個簡單的 View-based Application。
2、在 ViewController.xib 中加入三個標籤,建立 xlable、ylabel、zlabel 三個 IBOutlet。
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
補充:UIAccelerometer 的 updateInterval 預設較大,若需要更即時的反應,可在 viewDidLoad 中一併設定;而在 iOS 8 之後,Core Motion 是更推薦的做法。
在 iPhone 上執行程式,旋轉裝置即可看到三軸數值即時變化:
