Rotation only in one ViewController

后端 未结 13 1874
我在风中等你
我在风中等你 2020-12-05 03:20

I am trying to rotate one view while all other views (5) are fixed to portrait. The reason is that in that one view I want the user to watch pictures which he saved before.

13条回答
  •  独厮守ぢ
    2020-12-05 03:52

    With everyone's ideas I wrote the most elegant way to do it I think.

    Result:

        func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
            return (UIApplication.getTopViewController() as? Rotatable == nil) ? .portrait : .allButUpsideDown
        }
    

    Add this extension to your project which will always be useful not only for this:

    extension UIApplication {
    
        class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
            if let nav = base as? UINavigationController {
                return getTopViewController(base: nav.visibleViewController)
            }
    
            if let tab = base as? UITabBarController {
                if let selected = tab.selectedViewController {
                    return getTopViewController(base: selected)
                }
            }
    
            if let presented = base?.presentedViewController {
                return getTopViewController(base: presented)
            }
    
            return base
        }
    
    }
    

    Create the protocol:

    protocol Rotatable {}
    

    And implement it:

    class ViewController: UIViewController, Rotatable {
    }
    

提交回复
热议问题