【问题标题】:lock orientation of a viewController in swift快速锁定视图控制器的方向
【发布时间】:2016-05-15 16:52:57
【问题描述】:

我是 Swift 的新手,在 viewController 中将方向锁定为纵向时遇到问题。实际上我已经在我的自定义导航控制器中使用此代码锁定它

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if (self.visibleViewController is ViewController)
    {
        return UIInterfaceOrientationMask.Portrait
    }
    return .All
}

一切正常,ViewController 被锁定为纵向。问题是当从另一个以横向模式返回此控制器时。 如果我以横向返回 ViewController(从 NextViewController 按下),则 ViewController 出现在横向中。有什么建议吗?

【问题讨论】:

标签: ios swift locking orientation viewcontroller


【解决方案1】:

在 swift 3 中,此解决方案有效

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if self.window?.rootViewController?.presentedViewController is LockedViewController {
        return UIInterfaceOrientationMask.portrait
    } else {
        return UIInterfaceOrientationMask.all
    }
}

更改LockedViewController 以匹配您要锁定的控制器。

【讨论】:

  • 哇。这正是我想要的。非常感谢你发布这个!
【解决方案2】:

您可以覆盖以下方法

 override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait
  }
  override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    return UIInterfaceOrientation.Portrait
  }

然后,在您的 viewDidLoad 中,通过添加以下代码来强制定向

UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")

【讨论】:

  • 感谢您的回复。缺少的代码是 UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") 但它在 viewWillAppear 上效果更好。
【解决方案3】:

对于 swift3.0

要限制不同视图的不同方向,您需要执行以下操作:

在应用委托文件中:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {

        if self.window?.rootViewController?.presentedViewController is OtherViewController {

            return UIInterfaceOrientationMask.All;

        } else {
            return UIInterfaceOrientationMask.Portrait;
        }

    }

【讨论】:

  • 这在 Swift 4 中不起作用吗?实在不行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多