如何禁用ViewController的方向与UIApplication.keyWindow()

问题描述:

提出我有一个ViewController,可以在应用程序的任何地方呈现。我用这个代码UIApplication.sharedApplication().keyWindow?.rootViewController?.presentedViewController?.presentViewController来呈现它。所以我想禁用方向,只有肖像被支持。我已经尝试了很多解决方案,实施shouldAutorotate/supportedInterfaceOrientations/preferredInterfaceOrientationForPresentation,但没有任何帮助。任何人都面临这个问题如何禁用ViewController的方向与UIApplication.keyWindow()

你在viewDidLoad中试过这个吗?

viewDidLoad() { 
    let value = UIInterfaceOrientation.Portrait.rawValue 
    UIDevice.currentDevice().setValue(value, forKey: "orientation") 
    shouldAutorotate() 
} 
+0

试过但没有成功... – Slavcho

您是否尝试过在提交viewController之前设置设备方向?

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait]; 
[[UIDevice currentDevice] setValue:value forKey:@"orientation"]; 

,然后覆盖在你的 “介绍” 的viewController的shouldAutorotate方法并返回NO:

-(BOOL)shouldAutorotate 
{ 
    return NO; 
} 

或斯威夫特:

let value = UIInterfaceOrientation.Portrait.rawValue 
UIDevice.currentDevice().setValue(value, forKey: "orientation") 

override func shouldAutorotate() { 
    return false 
} 

你会看到一个旋转的动画,但它适用于我的应用程序。