viewWillTransitionToSize:withTransitionCoordinator:
似乎只在界面实际改变大小时才有效,这意味着我们已经旋转了90度。如果您的布局上有一个只允许横向的掩码,在旋转180度时,界面大小不会改变,因此该方法似乎不会被调用。
我在我的应用程序中通过注册UIDeviceOrientationDidChangeNotification
通知来解决这个问题,例如:
(在我的视图控制器的viewWillAppear
中):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
(在我的viewWillDisappear
函数中 [记得取消订阅])
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
我的 deviceOrientationDidChange:
看起来像这样:
- (void)deviceOrientationDidChange:(NSNotification *)notification {
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
[self willRotateToInterfaceOrientation:orientation duration:1.0];
}
- (void)deviceOrientationDidChange:(NSNotification *)notification {
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
NSLog(@"rotation %li", (long)orientation);
}
- Ford Davis按照文档,记得调用super
- (void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
// ...
}
否则,子视图控制器将无法接收到转发的消息。我知道这个问题现在有点过时了,但我认为对于那些可能遇到这个问题的人来说,还可以用另一种方法解决。如果您试图通过addSubview(controller.view)
加载属于其他控制器的视图,则还需要将该控制器添加到父控制器中(可能是您要添加到的视图的控制器)。如果您不将控制器添加到父级,则永远不会收到大小更改的更新。后来我们发现了苹果API更改的原因;使用iPad Pro时,您的SizeClass可以在多任务处理能力下无需旋转而更改。这也会调用该方法:
viewWillTransitionToSize(size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)