根据此处的
尽管
以下是完整的代码以进行复制:
UIViewController
文档,
使用[UIViewController attemptRotationToDeviceOrientation]
会强制系统尝试将界面旋转到新的方向。我正在尝试通过以下方式从竖屏强制旋转为横屏:
- 在尝试旋转之前设置
forceLandscape
标志 - 调用
[UIViewController attemptRotationToDeviceOrientation]
- 在我的视图控制器中实现
-supportedInterfaceOrientations
并检查一个标志以更改支持的方向,例如
这将强制再次调用-supportedInterfaceOrientations
,看起来像是
- (NSUInteger)supportedInterfaceOrientations {
return self.forceLandscape ? UIInterfaceOrientationMaskLandscapeLeft : UIInterfaceOrientationMaskPortrait;
}
尽管
-supportedInterfaceOrientations
被调用并返回新的方向,但接口不会旋转。我已确认该项目允许所有方向,并且此视图控制器是窗口的根视图控制器。是否有其他人遇到过这个问题并找到解决方案?我知道所有修复此问题的技巧(呈现和解除模态等),但如果可能的话,我希望有一个清晰的解决方案。我已在iOS 6和7上验证了此问题。以下是完整的代码以进行复制:
@interface ALTViewController ()
@property (nonatomic, assign) BOOL forceLandscape;
@end
@implementation ALTViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.forceLandscape = NO;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"button" forState:UIControlStateNormal];
[button sizeToFit];
[self.view addSubview:button];
button.center = self.view.center;
[button addTarget:self
action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonPressed:(id)sender
{
self.forceLandscape = YES;
[UIViewController attemptRotationToDeviceOrientation];
}
- (NSUInteger)supportedInterfaceOrientations
{
return self.forceLandscape ? UIInterfaceOrientationMaskLandscapeLeft : UIInterfaceOrientationMaskPortrait;
}