如何水平旋转设备,即使用户打开了纵向方向锁定



我想知道如何旋转设备,即使用户打开iPhone的纵向方向锁定。就像亚马逊prime视频应用一样,通常我看到的应用是纵向模式,但当我开始看电影时,即使我打开纵向方向锁定,应用也会将其旋转改为水平方向。

当我在谷歌上搜索时,我只找到了这篇文章,但是使用CoreMotion是实现我想要做的唯一方法??

我使用下面的代码来旋转本文中的设备,

struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
/// OPTIONAL Added method to adjust lock and rotate to the desired orientation
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
}
}

但是应用程序不会自动从纵向旋转到横向(从横向到纵向可以工作…),但是当我用手将设备从纵向旋转到横向时,应用程序的视图会旋转。

当我进入一个特定的视图控制器时如何让设备旋转到横向?(比如当我开始看电影时,prime视频应用会自动将方向转向横向)

在AppDelegate中跟随变量来锁定所有给定方向的控制器

var orientationLock  = UIInterfaceOrientationMask.portrait

现在在AppDelegate

中实现以下方法
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}

将这些方法写入单独的Helper文件

static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: LocalizedKey.orientation.string)
}

在特定控制器的viewWillAppear()中调用这个方法

override func viewWillAppear(_ animated: Bool) {
Helpers.lockOrientation(UIInterfaceOrientationMask.landscape,
andRotateTo: UIInterfaceOrientation.landscapeLeft)
}

注意:LocalizedKey.orientation.rawValue是单独文件中的字符串,其值为orientation">

最新更新