1

I hope you are well!

I am working on a Swift 2 app using Xcode FOR iOS 9! and I would like the whole app to rotate on both directions expect a particular view controller that I want to be locked to portrait even when the user rotates. I tried for hours and looked a lot online and nothing worked. Any help? UPDATE: I tried the two methods below but it doesn't work for iOS 9 :( Please help

Best, Anas

anasganim
  • 17
  • 1
  • 5

4 Answers4

3

Objective C :

NSNumber *orientationValue = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:orientationValue forKey:@"orientation"];

Swift :

let orientationValue = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(orientationValue, forKey: "orientation")
Community
  • 1
  • 1
Kemo
  • 488
  • 6
  • 12
  • 1
    Thanks, Kemo! But it's not working for me, where do I put the code? I tried this: override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let value = UIInterfaceOrientation.Portrait.rawValue UIDevice.currentDevice().setValue(value, forKey: "orientation") shouldAutorotate() } – anasganim Feb 08 '16 at 08:44
  • 1
    Just remove shouldAutorotate() and try override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let value = UIInterfaceOrientation.Portrait.rawValue UIDevice.currentDevice().setValue(value, forKey: "orientation") } – Kemo Feb 08 '16 at 11:25
  • This is a poor answer to current syntax for Swift4, no explanation and this doesnt work as @matt.writes.code has pointed out – Julian Silvestri Dec 31 '18 at 16:07
2
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait
}
ReMeDy
  • 99
  • 4
2

Try with this:

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

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

 func onlyPortarit() -> Bool{
    if(UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait ||
        UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown ||
        UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown){
            return true
    }else{
        return false
    }
 }
Manuel
  • 1,675
  • 12
  • 18
1

In addition to Manuel's response. Add the following in viewDidLoad()

UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")

This will initialize ViewController in portrait regardless of the device orientation.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
stoic0709
  • 11
  • 1