首页 > 解决方案 > 以编程方式更改 iOS 应用程序的方向

问题描述

当某事发生时,我如何以编程方式更改我的 iOS 应用程序的方向,例如当我按下按钮时,我需要我的设备去横向,并且在下次单击它时返回纵向。我尝试了这段代码,但什么也没发生

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

任何人都可以帮助我吗?

标签: iosswiftautolayout

解决方案


您可以将以下代码添加到 @IBAction 或您喜欢处理按钮按下的方式中

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    UIView.setAnimationsEnabled(false)
    UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
    UIView.setAnimationsEnabled(true)
  }

完整的解决方案在这里https://stackoverflow.com/a/50939184/9065909


推荐阅读