因为我的应用程序支持所有方向.我只想将肖像模式锁定到特定的UIViewController.
e、 g.假设它是选项卡式应用程序,当SignIn View以模式显示时,我只希望SignIn View处于纵向模式,无论用户如何旋转设备或当前设备方向如何
因为我的应用程序支持所有方向.我只想将肖像模式锁定到特定的UIViewController.
e、 g.假设它是选项卡式应用程序,当SignIn View以模式显示时,我只希望SignIn View处于纵向模式,无论用户如何旋转设备或当前设备方向如何
当您有一个复杂的视图层次 struct 时,事情可能会变得非常混乱,比如有多个导航控制器和/或选项卡视图控制器.
此实现将其置于各个视图控制器上,以设置它们希望锁定方向的时间,而不是依赖应用程序委托通过迭代子视图来查找方向.
Swift 3, 4, 5
在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 或助手类中,我创建了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)
}
If iPad or Universal App
Make sure that "Requires full screen" is checked in Target Settings -> General -> Deployment Info. supportedInterfaceOrientationsFor
delegate will not get called if that is not checked.