Tutorial iOS – Acelerômetro

On 23 de fevereiro de 2015 by Rafael Lage

Hoje iremos aprender a obter os valores fornecidos pelo acelerômetro. Ele é usado para detectar as diferenças na posição do dispositivo em três direções x, y e z. A partir desses valores descobrimos a posição do dispositivo em relação ao chão e para isso devemos usar um iPhone(não funciona no simulador). Para  isso siga os seguintes passos:

 

1- Crie uma Single View Based Application:

Captura de Tela 2015-01-23 às 21.46.26

2 – Crie as Labels para as direções x, y e z no seu ViewController.h:

[sourcecode language=”java”]
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIAccelerometerDelegate>
{
IBOutlet UILabel *xlabel;
IBOutlet UILabel *ylabel;
IBOutlet UILabel *zlabel;

}
@end
[/sourcecode]

3 – Faça as seguintes alterações no ViewController.m:

[sourcecode language=”java”]

#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

[/sourcecode]

3- Crie as labels em seu Main.storyboard e associe às labels criando no ViewController.h:

acelerometer

 

4- Pronto! Ao executar você terá o seguinte resultado:

acelerometro

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *