覆盖应用程序方向设置

Fre*_*ust 1 ios autolayout swift

我有一个应用程序,我仅在其目标设置中将方向设置为纵向:

在此处输入图片说明

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

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

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.AllButUpsideDown
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ang 5

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

我的灵感来自 Apple 的官方文档:supportedInterfaceOrientations

我的应用程序在 iPhone 上以纵向运行,在 iPad 上以所有方向运行。我只想要一个视图控制器(一个JTSImageViewController显示更大视图的图像)能够旋转。

信息表

Supported interface orientations = Portrait
Supported interface orientations (iPad) = Portrait, PortraitUpsideDown, LandscapeLeft, LandscapeRight
Run Code Online (Sandbox Code Playgroud)

如果应用委托实现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]
}
Run Code Online (Sandbox Code Playgroud)