3

I'm making an app which supports landscape orientations only when playing a video. Otherwise, all the scenes support only portrait orientation. I've checked portrait, landscape left and right in project settings. I've written the following code in the ViewControllers where I want to restrict to only portrait.

override func viewWillAppear(animated: Bool) {
    let value = UIInterfaceOrientation.Portrait.rawValue
    UIDevice.currentDevice().setValue(value, forKey: "orientation")
}

override func shouldAutorotate() -> Bool {
    return false
}

override func supportedInterfaceOrientations() -> Int {
    return UIInterfaceOrientation.Portrait.rawValue
}

Still, when I press (Command + right or left arrow), the simulator rotates. I don't have a device, so I have to test it in simulator.

Please help! Thank you!

Suvrat Apte
  • 161
  • 10
  • Are those methods getting called (set a breakpoint to check)? If you are using a navigation controller then they will only be getting called on the navigation controller. – dan Sep 23 '15 at 17:42
  • I am using a navigation controller. But they are getting called. I did put println() statements to ensure that they're getting called. – Suvrat Apte Sep 23 '15 at 18:01

2 Answers2

0

It's the parent navigation controller that decide if its content should rotate or note.

You will need to override UINavigationController and had something like this

override func shouldAutorotate() -> Bool {
    return self.topViewController.shouldAutorotae()
}

override func supportedInterfaceOrientations() -> Int {
    return self.topViewController.shouldAutorotae()
}
SeNeO
  • 417
  • 2
  • 9
  • Hey thank you so much @SeNeO ! It's working. But now there's another problem. If the user presses the back button from a video player in landscape mode, the previous VC does not rotate to portrait. viewWillAppear() is getting called. But it's not rotating to portrait. Please help! Thank you! – Suvrat Apte Sep 24 '15 at 04:43
  • I added the code in viewWillAppear() in its child view controller's willMoveToParentViewController(). It is working! Thank you @SeNeO – Suvrat Apte Sep 24 '15 at 05:13
  • Glad that had helped you. – SeNeO Sep 24 '15 at 15:53
0

Two things to check. First, check your info.plist file and make sure that you have portrait deleted for both iPhone and iPad. I was having the same issue and it was because I hadn't deleted the iPad "Portrait" options. See here:

enter image description here

Second, the below code can help. However, it may not work if you have a navigation controller.

override var shouldAutorotate: Bool {
    return true
}
Dave G
  • 12,042
  • 7
  • 57
  • 83