查看轮播通知:为什么didRotateFromInterfaceOrientation:没有被调用?
我正在尝试检测任何设备方向更改,以便我可以更新视图。
我想更新视图方向是纵向还是横向,所以我实现了这个方法:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft); }
我知道,如果我想更新视图以正确显示当前的方向,我将需要实现以下一些方法:
– willRotateToInterfaceOrientation:duration: – willAnimateRotationToInterfaceOrientation:duration: – didRotateFromInterfaceOrientation: – willAnimateFirstHalfOfRotationToInterfaceOrientation:duration: – didAnimateFirstHalfOfRotationToInterfaceOrientation: – willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:
现在,问题是,我不明白为什么这些方法没有被激发,当我旋转模拟器。
我也试过这段代码:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
但仍然没有。 所以我想知道,模拟器是否会启动轮转通知? 如果是的话,我在做什么错了?
你需要添加通知观察者的东西
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:) name:UIDeviceOrientationDidChangeNotification object:nil];
并添加该方法
- (void) didRotate:(NSNotification *)notification { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if (orientation == UIDeviceOrientationLandscapeLeft) { NSLog(@"Landscape Left!"); } }
快速总结,改变这个:
[window addSubview:viewController.view];
对此:
[window setRootViewController:viewController];
如果我把时间花在我的一个愚蠢的错误上,我感到抱歉。 我发现为什么方法– willRotateToInterfaceOrientation:duration:
永远不会被调用。 有些东西将我的注意力引向了导航控制器:
只有根视图控制器的willRotate方法被调用。 最有可能你有一个奇怪的视图控制器层次结构。
我在另一个论坛发现这些post,我看了一下应用程序的代表。 我的代码如下:
CGRect bound = [[UIScreen mainScreen] bounds]; window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, bound.size.width, bound.size.height)]; TestViewController *viewController = [[TestViewController alloc] init]; [window addSubview:viewController.view]; [viewController release]; [self.window makeKeyAndVisible];
问题是我没有为该窗口设置任何视图控制器,但我只是添加一个视图。 由于急于testing某些东西,我做了一个错误。 我不得不修正这样的代码:
CGRect bound = [[UIScreen mainScreen] bounds]; window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, bound.size.width, bound.size.height)]; TestViewController *viewController = [[TestViewController alloc] init]; [window setRootViewController:viewController]; [viewController release]; [self.window makeKeyAndVisible];