2016-04-01 25 views
0

我有一个应用程序,我设定的方向是纵向只在它的目标设置:覆盖应用方向设置

enter image description here

在一个特定的视图控制器我想重写此设置,以便自动布局将在设备旋转时更新视图。我试过这些方法没有成功:

override func shouldAutorotate() -> Bool { 
    return true 
} 

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { 
    return UIInterfaceOrientationMask.AllButUpsideDown 
} 
+0

恐怕没有比其他检查所有方向的项目设置,然后在除了需要一个 – heximal

+0

@heximal所有视图控制器限制他们的方式,请参阅接受的答案,这是相当不错的,不需要更新我所有的VC。 –

回答

2

您在所需的VC代码将无法正常工作。 我已通过添加以下代码的AppDelegate

var autoRotation: Bool = false 

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask { 
    return autoRotation ? .AllButUpsideDown : .Portrait 
    } 

然后你就可以做出一个辅助类,并添加这个方法管理这样的:在您需要的

class func setAutoRotation(value: Bool) { 
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { 
    appDelegate.autoRotation = value 
} 

}

最后VC,你可以在didDoad上调用setAutoRotation(true),在willDissapear上调用setAutoRotation(false)。

这也可以通过继承UINavigationController来实现。你可以找到答案here。 希望它有帮助

0

如果我已经阅读接受的答案,我不会写我自己的。我的版本更长,但只需要应用程序代理的方法application(_:supportedInterfaceOrientationsFor:)。它可能适用于您无法更改或不希望更改目标视图控制器的情况。例如,第三方视图控制器。

我是从苹果的官方文档的启发:supportedInterfaceOrientations

我的应用程序运行作为肖像在iPhone和iPad上的所有方向。我只想要一个视图控制器(一个JTSImageViewController呈现一个大图的图像)能够旋转。

的Info.plist

Supported interface orientations = Portrait 
Supported interface orientations (iPad) = Portrait, PortraitUpsideDown, LandscapeLeft, LandscapeRight 

如果应用程序委托实施application(_:supportedInterfaceOrientationsFor:),Info.plist中可能会被忽略。但是,我没有证实这一点。

斯威夫特4

func application(_ application: UIApplication, 
       supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { 
    // Early return for iPad 
    if UIDevice.current.userInterfaceIdiom == .pad { 
     return [.all] 
    } 
    // Search for the visible view controller 
    var vc = window?.rootViewController 
    // Dig through tab bar and navigation, regardless their order 
    while (vc is UITabBarController) || (vc is UINavigationController) { 
     if let c = vc as? UINavigationController { 
      vc = c.topViewController 
     } else if let c = vc as? UITabBarController { 
      vc = c.selectedViewController 
     } 
    } 
    // Look for model view controller 
    while (vc?.presentedViewController) != nil { 
     vc = vc!.presentedViewController 
    } 
    print("vc = " + (vc != nil ? String(describing: type(of: vc!)) : "nil")) 
    // Final check if it's our target class. Also make sure it isn't exiting. 
    // Otherwise, system will mistakenly rotate the presentingViewController. 
    if (vc is JTSImageViewController) && !(vc!.isBeingDismissed) { 
     return [.allButUpsideDown] 
    } 
    return [.portrait] 
}