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

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

技术教程推荐

趣谈网络协议 -〔刘超〕

深入剖析Kubernetes -〔张磊〕

算法面试通关40讲 -〔覃超〕

网络编程实战 -〔盛延敏〕

Netty源码剖析与实战 -〔傅健〕

互联网人的英语私教课 -〔陈亦峰〕

张汉东的Rust实战课 -〔张汉东〕

Redis源码剖析与实战 -〔蒋德钧〕

搞定音频技术 -〔冯建元 〕

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