如何强制iOS设备确定它';s通过陀螺仪定向?

如何强制iOS设备确定它';s通过陀螺仪定向?,ios,swift,uiviewcontroller,Ios,Swift,Uiviewcontroller,我的应用程序有时会强制特定的视图控制器以特定的方向显示 我发现的唯一方法是手动设置设备方向,并告诉应用程序尝试如下方式旋转自身: switch (forceOrientation){ case Orientations.PORTRAIT: let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation")

我的应用程序有时会强制特定的视图控制器以特定的方向显示

我发现的唯一方法是手动设置设备方向,并告诉应用程序尝试如下方式旋转自身:

switch (forceOrientation){
    case Orientations.PORTRAIT:
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    case Orientations.LANDSCAPE:
        let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    default:
        break
}
这个很好用。但是,一旦我关闭此视图控制器,并返回到上一个视图控制器,我仍然处于强制方向,无论设备如何固定。有没有办法将方向值设置为“脏”或什么,并让它自动检测

我已尝试将方向值设置为
UIInterfaceOrientation.unknown.rawValue
,然后尝试旋转,但这不起作用

我使用的是swift 4.1

--编辑--

为了进一步说明我在做什么:

创建“我的视图控制器”时,它将自己设置为根视图控制器(这样它的旋转设置将实际工作,否则根行为就是所使用的),在初始化过程中的某个点,可以告诉它应该以特定的方式定向。如果是这样,那么它会执行上面的代码,并适当地设置它的方向掩码。我正在使用这些覆盖:

public override var shouldAutorotate: Bool{
    return allowOrientationChange // this is set at some point after initializing
}

public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return orientationMask // this defaults to orientationMaskAll but is overridden 
}

关闭视图控制器时,上一个根控制器将添加回根控制器。(但它仍然会旋转到强制的位置,并且不会更新,除非您移动设备)

您可以覆盖
var-supportedInterfaceOrientationTask{get}
,并以在任何给定时间返回所需可用方向的方式进行设置

基本上,让此属性返回一个与
forceOrientation
enum相关的变量

有关详细信息,请参阅

要强制旋转,可以执行以下操作:

let previousOrientation = UIDevice.current.orientation  
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
//Rotates all view controllers
UIViewController.attemptRotationToDeviceOrientation()

//Find all UIViewControllers that need to be locked,  I recommend using a protocol


guard let appDelegate = UIApplication.sharedApplication().delegate, 
      let window = appDelegate.window, 
      let root = window.rootViewController,


else{
    fatalError("error")
} 
var viewControllers : [UIViewController] = []()
if root.presentedViewController != nil {
    viewControllers += [root.presentedViewController]
}
viewControllers += root.children
viewControllers.filter{$0 as OrientationLocked}.forEach{ vc in
  vc.orientationMask = ... //whatever previousOrientation isn't
}

//undo rotation
UIDevice.current.setValue(previousOrientation, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

//View controllers that had been filtered are now rotated, where as anything underneath were treated as if a rotation did not happen
。。。 任何可以锁定的视图控制器都需要此协议

protocol OrientationLocked {
    var orientationMask : UIInterfaceOrientationMask 
}