IOS加速度センサー(accelerometer)


概要

加速度センサーは、x、y、zの3方向に基づいて、デバイスの位置の変化を検出します。

加速度センサーによって、現在のデバイスの地面に対する位置を知ることができます。

以下のサンプルコードは実機で実行する必要があり、シミュレータでは動作しません。

サンプルの手順

1. 簡単なビューアプリケーションを作成します。

2. ViewController.xibに3つのラベルを追加し、それぞれxlable、ylabel、zlabelというibOutletsを作成します。

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デバイスでこのアプリケーションを実行すると、得られる出力結果は次のようになります。

accelerometer_Output

その他の拡張