View rotation notifications: why didRotateFromInterfaceOrientation: doesn't get called?

扶醉桌前 提交于 2019-11-30 11:44:47
Alkimake

You need to add notification observer something like

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:) name:UIDeviceOrientationDidChangeNotification object:nil];

and add the method

- (void) didRotate:(NSNotification *)notification
{   
      UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

       if (orientation == UIDeviceOrientationLandscapeLeft)
      {
        NSLog(@"Landscape Left!");
      }
}
Francesco Puglisi

Quick summary, change this:

[window addSubview:viewController.view];

to this:

[window setRootViewController:viewController];

I'm sorry if I took somebody's time for a silly mistake of mine. I found out why the method – willRotateToInterfaceOrientation:duration: would never get called. Something brought my attention to the navigation controller:

Only the root view controller's willRotate method is being called. Most likely you have a strange hierarchy of view controllers.

I found these post in another forum and I had a look at the app delegate. My code was as follows:

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

The problem was that I was not setting any view controller for the window, but I was just adding a view. It was a mistake I did due to the hurry to test something. I had to fix the code like this:

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!