iOS的横竖屏旋转

参考源

  1. 监听设备旋转方向 通过设备单例实现
    设备方向是根据Home键确定的
    必须先开始生成设备旋转方向的通知 然后监听通知 才可以处理设备的旋转
   //开启设备方向通知
        if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
            UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        }
 //注册通知   
        NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceOrientationChange(notification:)), name: .UIDeviceOrientationDidChange, object: nil)
 func handleDeviceOrientationChange(notification:NSNotification) -> Void {
        
        //获取设备方向
       //this will return UIDeviceOrientationUnknown unless device orientation notifications are being generated.
        let currentOri = UIDevice.current.orientation
        
        switch currentOri {
        case .faceUp:
            print("faceUp");
        case .faceDown:
            print("faceDown")
        case .landscapeLeft:
            print("landsapeLeft")
        case .landscapeRight:
            print("landscapeRight")
        case .portrait:
            print("portraint")
        case .portraitUpsideDown:
            print("portraintUpsideDown")
        case .unknown:
            print("unknown")
        }
    }
//移除通知
    deinit {
        //取消监听
        NotificationCenter.default.removeObserver(self)
        //关闭设备方向通知
        UIDevice.current.endGeneratingDeviceOrientationNotifications()
    }

  1. 监听屏幕旋转方向,
    如果要改变界面UI的话,大多情况这个更有用,因为如果设备发生旋转,但屏幕并未旋转就会出问题。
    屏幕方向是根据状态栏来判断的
//        用户界面方向是参考状态栏方向的UIApplication.shared.statusBarOrientation
//        注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(handleStatusBarOrientationChange(notification:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil)
    }
    
    
    func handleStatusBarOrientationChange(notification:NSNotification) -> Void {
        
       let interfaceor =  UIApplication.shared.statusBarOrientation
        
        switch interfaceor {
        case .portrait:
            print("portrait")
        case .portraitUpsideDown:
            print("portraintUpsideDown")
        case .landscapeLeft:
            print("landsacpeLeft")
        case .landscapeRight:
            print("landscapeRight")
        case .unknown:
            print("unknown")
        }
    }

控制器中常用的控制界面方向的方法

//    是否支持旋转
    override var shouldAutorotate: Bool{
        return true
    }
//    屏幕支持的旋转方向 UIInterfaceOrientation.portrait 表示仅支持竖直方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
        return UIInterfaceOrientationMask.all
    }
    
//    由模态推出的视图控制器 优先支持的屏幕方向
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return UIInterfaceOrientation.portrait
    }

你可能感兴趣的:(iOS的横竖屏旋转)