iPhone提供了3个机载的传感器,用于沿着iPhone的3根相互垂直的轴(左/右(x轴)、上/下(y轴)和前/后(z轴))度量加速能力。这些值指示作用于iPhone的力,它们来自重力和用户移动。可以通过在脑袋周围晃动iPhone(向心力)或者把它从高楼上投下(自由落体)来获得某种净力反馈。
要向iPhone加速计更新订阅某个对象,可把它设置委托。设置为委托的对象必须实现UIAccelerometerDelegate协议:
加速度传感器使用步骤如下:
①召唤UIAccelerometer这个单例;
②设置UIAccelerometer的updateInterval属性,就是设置通知间隔;
③向UIAccelerometer的delegate属性中设置负责具体处理的委托类;
④实现委托方法accelerometer:didAccelerate:以接受加速度的通知;
⑤从accelerometer:didAccelerate:方法的第二个参数UIAcceleration实例的相关属性中获取加速度
@interface ViewController () { UIImageView *arrow; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer]; accelerometer.updateInterval = 10.0/60.0; accelerometer.delegate =self; arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]]; [self.view addSubview:arrow]; }
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { //Determine up from the x and y acceleration components float xx = -acceleration.x; float yy = acceleration.y; float angle = atan2(yy, xx); [arrow setTransform:CGAffineTransformMakeRotation(angle)]; }