繁体   English   中英

如何将视图从纵向模式更改为横向模式并锁定它?

[英]how to change a view from portrait mode to landscape mode and lock it?

我有一个以纵向模式在右下角视口压缩的电影视图。 当用户展开影片视图时,影片视图将在横向模式下扩展到全屏。 我也想在全屏模式下将电影视图锁定为横向模式,无论设备的方向如何。

注意:我所有其他视图均为纵向模式。

我已经用这段代码引用了这篇文章

应用设置

在此处输入图片说明

AppDelegate.swift

internal var shouldRotate = false

func application(_ application: UIApplication,
                 supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return shouldRotate ? .allButUpsideDown : .portrait
}

视图控制器,

func expandPlayerWindow(button: UIButton) {
    self.player.view.frame = CGRect(x:0, y:-20, width: UIScreen.main.bounds.maxY, height: UIScreen.main.bounds.maxX)
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    print(appDelegate.shouldRotate)
    print(self.supportedInterfaceOrientations)
    appDelegate.shouldRotate = true // or false to disable rotation
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
    print(appDelegate.shouldRotate)
    print(self.supportedInterfaceOrientations)
    appDelegate.shouldRotate = false
    print(appDelegate.shouldRotate)
    print(self.supportedInterfaceOrientations)
    UIApplication.shared.isStatusBarHidden = false
}

日志,

false
UIInterfaceOrientationMask(rawValue: 26)
true
UIInterfaceOrientationMask(rawValue: 26)
false
UIInterfaceOrientationMask(rawValue: 26)

我在setorientation之前将shouldRotate设置为true,这可以使视图更改为横向模式。 设置方向后,我将shoudRotate设置为false以禁用旋转。 然后我对其进行测试,当我单击按钮时,电影视图将变为横向,在旋转设备后,电影视图将变为纵向,并锁定为纵向模式而不是横向模式。

是因为这个功能

func application(_ application: UIApplication,
                 supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return shouldRotate ? .allButUpsideDown : .portrait
}

改变.allButUpsideDown.landscape会做。

可行的代码,

AppDelegate.swift

func application(_ application: UIApplication,
                 supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return shouldRotate ? .landscape : .portrait
}

视图控制器,

func expandPlayerWindow() {
    self.player.view.frame = CGRect(x:0, y:-20, width: UIScreen.main.bounds.maxY, height: UIScreen.main.bounds.maxX)
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.shouldRotate = true // or false to disable rotation
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
    appDelegate.shouldRotate = true
    UIApplication.shared.isStatusBarHidden = true
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM