简体   繁体   English

使用UIAccelerometer切换视图

[英]Switching views using the UIAccelerometer

Hey guys, Sorry if I'm a newbie on this, I've looked around but haven't quite found out how to do it. 嘿伙计们,对不起,如果我是这个新手,我环顾四周,但还没有找到怎么做。 Basically I would like to switch views using the iphone's accelerometer. 基本上我想用iphone的加速度计切换视图。 For example, say if the iphone drops, the motion would trigger it to switch to another view telling the user the phone had dropped. 例如,假设iphone掉线,动作将触发它切换到另一个视图,告诉用户手机已经掉线。 Any help on how to do it would be appreciated, thanks. 任何有关如何做的帮助将不胜感激,谢谢。

The accelerometer can be read using UIAccelerometer class, which calls accelerometer values to its UIAccelerometerDelegate protocol delegate. 可以使用UIAccelerometer类读取加速度计,该类将加速度计值调用到其UIAccelerometerDelegate协议代理。 This means: 这意味着:

h file: h文件:

@interface TestView: UIViewController <UIAccelerometerDelegate> {
  UIAccelerometer *accelerometer;
}

@property (nonatomic, retain) UIAccelerometer *accelerometer;

@end

in your m file: 在你的m文件中:

- (void)viewDidLoad {
  [super viewDidLoad];

  self.accelerometer = [UIAccelerometer sharedAccelerometer];
  self.accelerometer.updateInterval = .1;
  self.accelerometer.delegate = self;
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {     
  float aX = ABS(acceleration.x);
  float aY = ABS(acceleration.y);
  float aZ = ABS(acceleration.z);
  if(sqrt(aX*aX+aY*aY+aZ*aZ)>THRESHOLD){
     //Load new view here      
  }
}

You can choose THRESHOLD to be anything you want it to be. 你可以选择THRESHOLD成为你想要的任何东西。 It implies that the length of the acceleration vector exceeds a certain value. 这意味着加速度矢量的长度超过某个值。 I think this value is usually around 1 if there is no movement, and higher if there is some movement. 我认为如果没有运动,这个值通常在1左右,如果有运动则更高。 I would recommend setting this to something like 1.5 maybe? 我建议将此设置为1.5或许可能? You can try out different values yourself. 您可以自己尝试不同的值。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM