Making UIAccelerometer work more than once when switching views
I need help with a problem and not sure how to fix it. Basically I have a view which switches to another view by using the accelerometer, the problem is it only works once. When I go back to the first view, the accelerometer won't work again until i rebuild the project.
This is the method I use:
- (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)&g开发者_StackOverflowt;1.5f)
{
SecondViewController *screen = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//screen.words = self.easy;
[self presentModalViewController:screen animated:YES];
[screen release];
self.accelerometer.delegate = nil;
}
Any kind of help would be much appreciated.
You could set up a BOOL to temporarily disable the accelerometer handling when you present the new view controller and avoid calling self.accelerometer.delegate = nil
Once the modal transition is done, you can re-enable the accelerometer handling
Edit - Example:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
if(accelerometerEnabled) {
//... the accelerometer data handling goes here
}
Also, it looks like I did not understand all of the question originally - you'll also need to reset the accelerometer delagate to whatever view controller you want to use to handle the acceleration data. That (second) view controller will have to have the -(void)accelerometer delegate method also.
Alternatively, you could handle the acceleration data in a root view controller and make your views subviews of that root view. That would be cleaner, as you would never have to change which controller is handling the acceleration.
精彩评论