How to force view controller orientation in iOS 8?

前端 未结 25 2381
太阳男子
太阳男子 2020-11-22 13:11

Before iOS 8, we used below code in conjunction with supportedInterfaceOrientations and shouldAutoRotate delegate methods to force app orie

25条回答
  •  一生所求
    2020-11-22 13:23

    This way work for me in Swift 2 iOS 8.x:

    PS (this method dont require to override orientation functions like shouldautorotate on every viewController, just one method on AppDelegate)

    Check the "requires full screen" in you project general info.

    So, on AppDelegate.swift make a variable:

    var enableAllOrientation = false
    

    So, put also this func:

    func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
            if (enableAllOrientation == true){
                return UIInterfaceOrientationMask.All
            }
            return UIInterfaceOrientationMask.Portrait
    }
    

    So, in every class in your project you can set this var in viewWillAppear:

    override func viewWillAppear(animated: Bool)
    {
            super.viewWillAppear(animated)
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            appDelegate.enableAllOrientation = true
    }
    

    If you need to make a choices based on the device type you can do this:

    override func viewWillAppear(animated: Bool)
        {
            super.viewWillAppear(animated)
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            switch UIDevice.currentDevice().userInterfaceIdiom {
            case .Phone:
            // It's an iPhone
               print(" - Only portrait mode to iPhone")
               appDelegate.enableAllOrientation = false
            case .Pad:
            // It's an iPad
               print(" - All orientation mode enabled on iPad")
               appDelegate.enableAllOrientation = true
            case .Unspecified:
            // Uh, oh! What could it be?
               appDelegate.enableAllOrientation = false
            }
        }
    

提交回复
热议问题