Search code examples
swift3iso

Support landscape and portrait device orientation for specific view controller in ios, swift 3


I am working on an iOS application, in which all ViewControllers support only Portrait orientation, except one ViewController, which supports both Portrait and landscape. I try this code for that ViewController

 override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscapeLeft
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .landscapeLeft
}

but this didn't work, Can any one help ? thanks


Solution

  • in AppDelegate add this event

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    
    
        if let navigationController = UIApplication.topViewController() {
    
            if navigationController is YOURVIEWCONTROLLERNAME  {
                return UIInterfaceOrientationMask.all
            }
    
            else {
                return UIInterfaceOrientationMask.portrait
            }
        }
    
        return UIInterfaceOrientationMask.portrait
    }
    
    extension UIApplication {
    class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topViewController(base: selected)
            }
        }
        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }
        return base
    }
    

    change YOURVIEWCONTROLLERNAME to your view controller