在Portrait - Swift 3中仅横向应用一个控制器

时间:2017-03-07 12:09:42

标签: uiviewcontroller swift3 orientation landscape-portrait

在App代表中:

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

在我的View Controller(MainViewController)中,我添加了

override func viewDidLoad() {
    super.viewDidLoad()

    let value = UIInterfaceOrientation.portrait.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
    supportedInterfaceOrientations()
    preferredInterfaceOrientationForPresentation()
    // Do any additional setup after loading the view.
}

private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask(rawValue: UIInterfaceOrientationMask.portrait.rawValue)
}

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

private func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {

    // Only allow Portrait
    return UIInterfaceOrientation.portrait
}

这是我想在纵向模式下工作的应用程序中唯一的控制器。除了景观模式中的一切。

但是我尝试过很多事情仍然无法理解为什么它不起作用。

提前致谢。很抱歉在swift中成为菜鸟。

1 个答案:

答案 0 :(得分:1)

在appdelegate中编写此代码

var shouldRotate = false
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if shouldRotate {
        return .landscape
    }
    else {
        return .portrait
    }
}

在viewDidload()

中将此代码设置为视图控制器
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.shouldRotate = true // or false to disable rotation
    //you can manage only changing true or false 

希望它可以帮助您

相关问题