// This method is called every time the device changes orientation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
}
- (void)viewWillLayoutSubviews {
[self checkIfOrientationChanged];
}
- (void)checkIfOrientationChanged {
UIInterfaceOrientation newOrientation = [[UIApplication sharedApplication] statusBarOrientation];
BOOL newOrientationIsPortrait = UIInterfaceOrientationIsPortrait(newOrientation);
BOOL oldOrientationIsPortrait = UIInterfaceOrientationIsPortrait(_currentOrientation);
// Check if the orientation is the same as the current
if(newOrientationIsPortrait != oldOrientationIsPortrait){
_currentOrientation = newOrientation;
// Do some stuff with the new orientation
}
}
6 回答
您可以在这里阅读一些可能的原因:
Technical Q&A QA1688 - Why won't my UIViewController rotate with the device?
在您的情况下,可能是您将视图作为另一个子视图添加到窗口 . 只有第一个子视图才能获得旋转事件 . 您可以做的是将其添加为第一个窗口子视图的子视图 .
问题
https://developer.apple.com/library/content/qa/qa1688/_index.html
解决方案
我已经开源了一个名为AGWindowView的pod .
它将自动处理任何旋转和帧更改,因此您不必担心这一点 .
代码
它支持SDK和iOS系统版本的任意组合 . 相关代码可在此处找到:https://github.com/hfossli/AGWindowView/blob/master/Source/AGWindowView.m
我在UIApplication上创建了一个类别,它有一个辅助属性和方法来获取keyWindow的第一个子视图 . 无论如何,这是您要叠加的视图 . 现在,当您将由UIViewController管理的视图添加到该视图时,将调用shouldRotateToInterfaceOrientation:方法 .
UIApplication WindowOverlay.h
UIApplication WindowOverlay.m
以下是您将如何使用它 .
这是因为正如您所提到的,您的视图已直接添加到UIWindow,因此当为导航控制器调用旋转方法时,uiview没有任何反应 . 如果UIView是视图控制器视图的子视图,它将旋转 . 如果由于某种原因无法做到这一点 . 然后你可以覆盖这个方法:
每次您的方向更改也会改变您的视图方向 .
我有一个类似的问题,直接添加到窗口的视图 . 也许这会有所帮助:Automatically Sizing UIView after Adding to Window
我解决这个问题的另一个解决方案 .
定义当前方向:
然后检查viewWillLayoutSubviews中的方向: