iOS - 加速計



加速計用於檢測裝置在 x、y 和 z 三個方向的位置變化。我們可以知道裝置相對於地面的當前位置。要測試此示例,您需要在裝置上執行它,它不能在模擬器上工作。

加速計 - 涉及的步驟

第 1 步 - 建立一個簡單的基於檢視的應用程式

第 2 步 - 在 ViewController.xib 中新增三個標籤,並建立名為 xlabel、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

輸出

當我們在 iPhone 裝置中執行應用程式時,將會獲得以下輸出 -

iOS Tutorial
廣告