如何解决在 Swift 中的特定视图控制器中锁定应用程序的方向
我正在开发一个需要在每个视图控制器中锁定方向的应用程序。 我阅读了 this article,但它对我不起作用。 在项目设置中,我将设备方向设置为纵向、横向左侧和横向右侧。
我有两个视图控制器,VC1 和 VC2,我只想垂直锁定 VC1 的方向。我想锁定 VC2 的方向,另一方面,仅水平方向。
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait //return the value as per the required orientation
}
override var shouldAutorotate: Bool {
return false
}
但是,我仍然可以水平旋转 VC1... 旁注:VC1 包含一个导航栏和一个标签栏。
如果您知道如何解决此问题,请告诉我...
解决方法
您可以通过几个步骤强制定向:
首先,在您的 AppDelegate
中定义一个方向属性并符合 supportedInterfaceOrientationsFor
var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication,supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
然后声明实用程序结构以使用 KVO 设置方向:
struct AppOrientationUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask,andRotateTo rotateOrientation: UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue,forKey: "orientation")
}
}
使用方法:
//For portrait
AppOrientationUtility.lockOrientation(UIInterfaceOrientationMask.portrait,andRotateTo: UIInterfaceOrientation.portrait)
//For landscape
AppOrientationUtility.lockOrientation(UIInterfaceOrientationMask.landscapeRight,andRotateTo: UIInterfaceOrientation.landscapeRight)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。