I have an UIViewController, I want to disable or enable rotation of the screen in different scenarios
Example:
if flag {
rotateDevice = false
}
e
In swift 5, as from previous, if you want to allow (avoid others) a particular UIViewController to rotate in a certain orientation you have to override "supportedInterfaceOrientations" inside your UIViewController class like so:
class MyViewController:UIViewController{
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get{
return .portrait
}
}
}
Here there are the possible options:
public struct UIInterfaceOrientationMask : OptionSet {
public init(rawValue: UInt)
public static var portrait: UIInterfaceOrientationMask { get }
public static var landscapeLeft: UIInterfaceOrientationMask { get }
public static var landscapeRight: UIInterfaceOrientationMask { get }
public static var portraitUpsideDown: UIInterfaceOrientationMask { get }
public static var landscape: UIInterfaceOrientationMask { get }
public static var all: UIInterfaceOrientationMask { get }
public static var allButUpsideDown: UIInterfaceOrientationMask { get }
}
Extended
If you want to be able to distinguish between iPad or iPhone you could use UIUserInterfaceIdiom:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get{
return UIDevice.current.userInterfaceIdiom == .phone ? [.portrait, . portraitUpsideDown]:.all //OBS -> You can also return an array
}
}
where:
public enum UIUserInterfaceIdiom : Int {
case unspecified
@available(iOS 3.2, *)
case phone // iPhone and iPod touch style UI
@available(iOS 3.2, *)
case pad // iPad style UI
@available(iOS 9.0, *)
case tv // Apple TV style UI
@available(iOS 9.0, *)
case carPlay // CarPlay style UI
}