Created
March 13, 2020 12:10
-
-
Save hamdan/ca166cc7aa7cfda6ae4b0434031a2a13 to your computer and use it in GitHub Desktop.
Rotate Only One ViewController to Landscape Orientation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. First of all, you need to make sure “Device Orientation” only on ‘Portrait’ mode. | |
//2. Add these two functions to AppDelegate, which helps you deal with embed in nav bar/tab bar situation mentioned above: | |
protocol Rotatable: AnyObject { | |
func resetToPortrait() | |
} | |
extension Rotatable where Self: UIViewController { | |
func resetToPortrait() { | |
UIDevice.current.setValue(Int(UIInterfaceOrientation.portrait.rawValue), forKey: "orientation") | |
} | |
func setToLandscape() { | |
UIDevice.current.setValue(Int(UIInterfaceOrientation.landscapeLeft.rawValue), forKey: "orientation") | |
} | |
} | |
extension AppDelegate { | |
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { | |
guard | |
let _ = topViewController(for: window?.rootViewController) as? Rotatable | |
else { return .portrait } | |
return .allButUpsideDown | |
} | |
private func topViewController(for rootViewController: UIViewController!) -> UIViewController? { | |
guard let rootVC = rootViewController else { return nil } | |
if rootVC is UITabBarController { | |
let rootTabBarVC = rootVC as! UITabBarController | |
return topViewController(for: rootTabBarVC.selectedViewController) | |
} else if rootVC is UINavigationController { | |
let rootNavVC = rootVC as! UINavigationController | |
return topViewController(for: rootNavVC.visibleViewController) | |
} else if let rootPresentedVC = rootVC.presentedViewController { | |
return topViewController(for: rootPresentedVC) | |
} | |
return rootViewController | |
} | |
} | |
// 3. Finally, go to the specific view controller you planned to allow rotate | |
import UIKit | |
final class ABCViewController: UIViewController, Rotatable { | |
override func viewWillDisappear(_ animated: Bool) { | |
super.viewWillDisappear(animated) | |
resetToPortrait() | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
setToLandscape() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment