This is a generic solution for your problem and others related.
1. Create auxiliar class UIHelper and put on the following methods:
class func topViewController() -> UIViewController?
{
let helper = UIHelper()
return helper.topViewControllerWithRootViewController(rootViewController: UIApplication.shared.keyWindow?.rootViewController)
}
private func topViewControllerWithRootViewController(rootViewController:UIViewController?) -> UIViewController?
{
if(rootViewController != nil)
{
if let tabBarController = rootViewController as? UITabBarController,
let selectedViewController = tabBarController.selectedViewController {
return self.topViewControllerWithRootViewController(rootViewController: selectedViewController)
}
if let navigationController = rootViewController as? UINavigationController ,let visibleViewController = navigationController.visibleViewController {
return self.topViewControllerWithRootViewController(rootViewController: visibleViewController)
}
if ((rootViewController!.presentedViewController) != nil) {
let presentedViewController = rootViewController!.presentedViewController;
return self.topViewControllerWithRootViewController(rootViewController: presentedViewController!);
}else
{
return rootViewController
}
}
return nil
}
2. Create a Protocol with your desire behavior, for your specific case will be portrait.
protocol orientationIsOnlyPortrait {}
Nota: If you want, add it in the top of UIHelper Class.
3. Extend your View Controller
In your case:
class Any_ViewController: UIViewController,orientationIsOnlyPortrait {
....
}
4. In app delegate class add this method:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
let presentedViewController = UIHelper.topViewController()
if presentedViewController is orientationIsOnlyPortrait {
return .portrait
}
return .all
}
Final Notes:
- If you that more class are in portrait mode, just extend that
protocol.
- If you want others behaviors from view controllers, create other protocols and follow the same structure.
- This example solves the problem with orientations changes after push
view controllers