Swift 4仅旋转UITabBarController的一个屏幕

时间:2018-09-19 14:47:16

标签: swift

我有一个UITabBarController类,并且只希望其中一个ViewController旋转,所有其他ViewController都应始终以纵向模式显示。

当从RotateViewController切换到横向的另一个ViewController时,无论旋转如何,屏幕都将保持横向。切换屏幕时,似乎没有“重新评估”正确的旋转。

class TabBarController: UITabBarController {

override var shouldAutorotate: Bool {
    if self.selectedViewController is RotateViewController {
        return true
    }
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if self.selectedViewController is RotateViewController {
        return [.portrait, .landscapeRight, .landscapeLeft]
    }
    return .portrait
}

强制旋转不起作用。这将在横向中渲染所有单独的元素,然后旋转整个屏幕。

UIDevice.current.setValue(Int(UIInterfaceOrientation.portrait.rawValue), forKey: "orientation")

1 个答案:

答案 0 :(得分:0)

AppDelegate

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
        if (rootViewController.responds(to: Selector(("canRotate")))) {
            return .allButUpsideDown;
        }
    }

    return .portrait;
}

private func topViewControllerWithRootViewController(rootViewController: UIViewController!) -> UIViewController? {
    if (rootViewController == nil) { return nil }
    if (rootViewController.isKind(of: UITabBarController.self)) {
        return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UITabBarController).selectedViewController)
    } else if (rootViewController.isKind(of: UINavigationController.self)) {
        return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UINavigationController).visibleViewController)
    } else if (rootViewController.presentedViewController != nil) {
        return topViewControllerWithRootViewController(rootViewController: rootViewController.presentedViewController)
    }
    return rootViewController
}

在您的 ViewController 中添加

override func viewDidLoad {
    super.viewDidLoad()

    self.canRotate()
}

@objc func canRotate() -> Void {}