我希望只有一个Viewcontroller以横向模式显示

时间:2016-12-11 10:30:02

标签: ios swift ios10

我目前正在开发一款移动应用程序,该应用程序只能锁定在纵向模式下。我可以在我的项目设置中执行此操作,这不是问题,但我希望一个Viewcontroller仅以横向模式显示。

我尝试在项目设置中禁用纵向模式,并将这段代码添加到我的横向视图控制器(以及调用它的纵向控制器):

let value =  UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

我现在面临的问题是,这个解决方案不是最佳的。用户仍然可以旋转他的设备。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

尝试锁定自动旋转

NULL

答案 1 :(得分:0)

这在iOS10之前有效

viewdidload:

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

在viewcontroller中也有这个:

override var shouldAutorotate : Bool {
    return true
}

override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.landscapeRight
}

override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
    return UIInterfaceOrientation.landscapeRight
}

答案 2 :(得分:0)

下面的代码可以正常使用。

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
        if (rootViewController.responds(to: Selector(("canRotate")))){
            // Unlock landscape view orientations for this view controller
            return .allButUpsideDown
        }
    }
    // Only allow portrait (standard behaviour)
    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}} .
 //Add the below method in ViewController .   

@objc func canRotate() -> Void {}