如何旋转到仅一个视图控制器横向

时间:2019-05-13 10:19:11

标签: ios swift

我使用以下方法使其可行,但是没有用

override func viewDidLoad() {
    super.viewDidLoad()
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscapeLeft
}

override var shouldAutorotate: Bool {
    return true
}    

2 个答案:

答案 0 :(得分:1)

如果要强制将特定的viewController仅旋转为横向,则在AppDelega文件中添加以下代码

public var orientationLock = UIInterfaceOrientationMask.all

    static var shared : AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }


    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientationLock
    }

    func lockDeviceOrientation(orientationLock: UIInterfaceOrientationMask, rotateOrientation:UIInterfaceOrientation) {
        AppDelegate.shared.orientationLock = orientationLock
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }

并在要强制仅横向旋转的特定viewController中添加以下代码

 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        AppDelegate.shared.orientationLock = .landscapeLeft
    }

答案 1 :(得分:0)

在您的AppDelegate.swift中:

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if let navigationController = self.window?.rootViewController as? UINavigationController {
        if navigationController.visibleViewController is YourViewController {
            return UIInterfaceOrientationMask.all
        } else {
            return UIInterfaceOrientationMask.portrait
        }
    }
    return UIInterfaceOrientationMask.portrait
}