iOS版。 如何在每个UIViewController上启用和禁用旋转?
我有一个UIViewController,我想在不同的场景中禁用或启用屏幕旋转
例:
if flag { rotateDevice = false } else { rotateDevice = true }
我怎样才能做到这一点?
我有答案。 在AppDelegate
,如果您旋转设备,请按viewcontroller等。此函数始终调用
更新swift 3/4
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return self.restrictRotation }
self.restrictRotation
是一个自定义参数。
如何使用:
在Appdelegate:
var restrictRotation:UIInterfaceOrientationMask = .portrait
在ViewController中:
调用方法ViewDidLoad或viewWillAppear时。 我们将改变如下:
(UIApplication.shared.delegate as! AppDelegate).restrictRotation = .all
然后将调用AppDelegate上的此方法。
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask
您只需在您的UIViewController
实现shouldAutorotate
和supportedInterfaceOrientations
。 看一下这个文档 。 例如:
override func shouldAutorotate() -> Bool { return true }
您还可以指定可用的方向。 这是一个只有肖像方向的例子:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .Landscape }
编辑:如果你想支持关于旗帜的不同方向,你只需要做这样的事情:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if myFlag { return .Landscape } else { return .All } }
(如果myFlag
为true,则允许Landscape
定向。否则,它将允许所有方向)。
迅速4
override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return .portrait } }
在Target – > General – > Deployment Info – > Portrait中设置设备orientarion肖像