iOS. How to enable and disable rotation on each UIViewController?

后端 未结 8 2123
栀梦
栀梦 2020-12-13 04:10

I have an UIViewController, I want to disable or enable rotation of the screen in different scenarios

Example:

if flag {
   rotateDevice = false
}
e         


        
8条回答
  •  Happy的楠姐
    2020-12-13 04:56

    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
    }
    

提交回复
热议问题