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)]; }