由于我的应用程序支持所有方向。我只想将肖像模式锁定到特定的UIViewController。
例如,假设它是“选项卡式应用程序”,并且当SignIn View模态显示时,无论用户如何旋转设备或当前设备的方向如何,我都只希望SignIn View进入纵向模式
当您具有复杂的视图层次结构时,事情会变得很混乱,例如具有多个导航控制器和/或选项卡视图控制器。
此实现将其置于各个视图控制器上,以便在它们希望锁定方向时进行设置,而不是依赖于App Delegate通过遍历子视图来找到它们。
斯威夫特3&4
在AppDelegate中:
/// set orientations you want to be allowed in this property by default var orientationLock = UIInterfaceOrientationMask.all func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return self.orientationLock }
在其他一些全局struct或helper类中,我在这里创建了AppUtility:
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() } }
然后在所需的ViewController中,您要锁定方向:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) AppUtility.lockOrientation(.portrait) // Or to rotate and lock // AppUtility.lockOrientation(.portrait, andRotateTo: .portrait) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Don't forget to reset when view is being removed AppUtility.lockOrientation(.all) }
如果是iPad或Universal App
确保在“目标设置”->“常规”->“部署信息”中选中了“需要全屏显示”。supportedInterfaceOrientationsFor如果未选中,则不会调用委托。
supportedInterfaceOrientationsFor