强制方向在iOS 10设备中不起作用

目前,我正在做AVPlayer全屏button按下时强制方向的变化。我尝试了类似的东西

final class NewMoviePlayerViewController: AVPlayerViewController { override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if contentOverlayView?.bounds == UIScreen.main.bounds{ DispatchQueue.main.async { let value = UIInterfaceOrientation.landscapeRight.rawValue UIDevice.current.setValue(value, forKey: "orientation") } print("full screen") }else{ DispatchQueue.main.async { let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") } print("half screen") } } } 

上面的代码在iOS 11中工作正常,但相同的代码不工作在iOS 10和以下版本

我们终于用下面的方法解决了

我们在AppDelegate上使用了一个Boolvariables来检测方向的变化。

 var isLandScapeManualCheck = Bool() 

接下来我们实现了下面的应用程序委托

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

基于布尔值,我们已经返回了定向模式。

iOS 10及以下版本应该遵循这种方式..

在你的playercontroller视图..(意思是你的家庭控制器)

 if #available(iOS 11, *) { }else{ playerVwController.contentOverlayView!.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions.new, context: nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "bounds"{ let rect = change![.newKey] as! NSValue if let playerRect: CGRect = rect.cgRectValue as CGRect { if playerRect.size == UIScreen.main.bounds.size { print("Player in full screen") let value = UIInterfaceOrientation.landscapeLeft.rawValue UIDevice.current.setValue(value, forKey: "orientation") isLandScapeManualCheck = true } else { DispatchQueue.main.async { let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") print("Player not in full screen") isLandScapeManualCheck = false } } } } } 

在iOS 11之后

你应该调用viewDidLayoutSubviews

  UIViewController.attemptRotationToDeviceOrientation() 

所以最后你的子类代码如下所示

 final class NewMoviePlayerViewController: AVPlayerViewController { override func viewDidLayoutSubviews() { UIViewController.attemptRotationToDeviceOrientation() super.viewDidLayoutSubviews() if contentOverlayView?.bounds == UIScreen.main.bounds{ DispatchQueue.main.async { let value = UIInterfaceOrientation.landscapeRight.rawValue UIDevice.current.setValue(value, forKey: "orientation") } // self.contentOverlayView?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)) print("full screen") }else{ DispatchQueue.main.async { let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") } // self.contentOverlayView?.transform = CGAffineTransform.identity print("half screen") } } }