To lock a viewController in a mode do the following:
In your AppDeletegate add:
var shouldSupportAllOrientation = false
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
if (shouldSupportAllOrientation == true){
return UIInterfaceOrientationMask.All
}
return UIInterfaceOrientationMask.Portrait
}
Now go to each view and add the following in viewWillAppear
:
Portait mode only
let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = false
All modes
let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = true
Update
If you want to go from landscape back to portrait again when you change view/tab, add the following code
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
Swift 3.x version
Add this in your AppDelegate class
var shouldSupportAllOrientation = false
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if (shouldSupportAllOrientation == true){
return UIInterfaceOrientationMask.all
}
return UIInterfaceOrientationMask.portrait
}
Add this in your viewController
// Portrait mode
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = false
// All modes
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = true
Swift 4 version:
In your AppDelegate, add the following:
var shouldSupportOrientation: UIInterfaceOrientationMask = .portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return shouldSupportOrientation
}
In each viewController add the following:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.shouldSupportOrientation = .portrait // set desired orientation
let value = UIInterfaceOrientation.portrait.rawValue // set desired orientation
UIDevice.current.setValue(value, forKey: "orientation")
}
This will lock your view and rotate it.