6

I'm a newbie in Swift and i have a problem locking the orientation to portrait in a viewController. Actually i have locked it using this code in my Custom Navigation Controller

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if (self.visibleViewController is ViewController)
    {
        return UIInterfaceOrientationMask.Portrait
    }
    return .All
}

Everything works fine and the ViewController is locked to portrait.The problem is when return to this controller from another in landscape mode. if i return to ViewController (pressing back from the NextViewController) in landscape then the ViewController appeared in landscape. Any suggestion?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
aris ppspr
  • 119
  • 3
  • 11

3 Answers3

8

In swift 3 this solution works

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if self.window?.rootViewController?.presentedViewController is LockedViewController {
        return UIInterfaceOrientationMask.portrait
    } else {
        return UIInterfaceOrientationMask.all
    }
}

Change LockedViewController to match the controller you would like locked.

Ahmad Amin
  • 191
  • 2
  • 12
0

You can override the methods below

 override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait
  }
  override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    return UIInterfaceOrientation.Portrait
  }

Then, in your viewDidLoad, force the orientation by adding the code below

UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")
Karlo P
  • 11
  • 1
  • 1
  • thank's for your reply. The missing code was UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") but it works better on viewWillAppear. – aris ppspr May 16 '16 at 15:22
0

For swift3.0

To restrict different orientations for different views You need to do following things :

In App delegate File :

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {

        if self.window?.rootViewController?.presentedViewController is OtherViewController {

            return UIInterfaceOrientationMask.All;

        } else {
            return UIInterfaceOrientationMask.Portrait;
        }

    }
Ash
  • 5,525
  • 1
  • 40
  • 34