iOS – 加速度计

简述

加速度计用于检测设备在 x、y 和 z 三个方向上的位置变化。我们可以知道设备相对于地面的当前位置。为了测试这个例子,你需要在一个device 并且在模拟器上不起作用。

加速度计 - 涉及的步骤

步骤 1 - 创建一个简单的 View based application.
步骤 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];
// 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 教程
以上是iOS – 加速度计的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>