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. For example, say if the iphone drops, the motion would trigg开发者_Python百科er it to switch to another view telling the user the phone had dropped. 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. This means:
h file:
@interface TestView: UIViewController <UIAccelerometerDelegate> {
UIAccelerometer *accelerometer;
}
@property (nonatomic, retain) UIAccelerometer *accelerometer;
@end
in your m file:
- (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. 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. I would recommend setting this to something like 1.5 maybe? You can try out different values yourself.
Hope this helps!
精彩评论