OC - 加速传感器

OC - 加速传感器 首页 / iOS入门教程 / OC - 加速传感器

Accelerometer计用于检测设备在三个方向x,y和z上的位置变化,无涯教程可以知道设备相对于地面的当前位置,为了测试该示例,您需要在设备上运行它,并且不能在模拟器上运行。

示例的步骤

第1步  -  创建一个简单的基于视图的应用程序。

第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];
   //处置任何可以重新创建的资源。
}

- (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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

深入浅出gRPC -〔李林锋〕

黄勇的OKR实战笔记 -〔黄勇〕

后端技术面试 38 讲 -〔李智慧〕

分布式数据库30讲 -〔王磊〕

手机摄影 -〔@随你们去〕

小马哥讲Spring AOP编程思想 -〔小马哥〕

手把手带你搭建秒杀系统 -〔佘志东〕

AI大模型系统实战 -〔Tyler〕

好记忆不如烂笔头。留下您的足迹吧 :)