Swift之家

Swift获取手机屏幕方向

2017-04-20  本文已影响57人  小小土豆dev

Swift中获取手机屏幕方向,和Object-C中类似。屏幕方向改变时,系统会发出通知,我们只要在 ViewController 里注册屏幕方向改变的通知即可。

1.注册通知

//注册手机屏幕方向切换的通知

NotificationCenter.default.addObserver(self,

                                              selector:#selector(ViewController.orientationChanged(_:)),

                                           name:NSNotification.Name.UIDeviceOrientationDidChange,

                                              object:nil)

2.通知实现方法

funcorientationChanged(_notification:NSNotification) {

   //获得当前运行中设备信息

   letdevice =UIDevice.current

   //遍历设备屏幕方向

   switchdevice.orientation{

   case.portrait:

       print("设备屏幕位于垂直方面,Home键位于下方")

   case.portraitUpsideDown:

        print("设备屏幕位于垂直方面,Home键位于上方")

   case.landscapeLeft:

       print("设备屏幕位于水平方面,Home键位于右侧")

   case.landscapeRight:

      print("设备屏幕位于水平方面,Home键位于左侧")

   case.faceUp:

       print("设备处于平放,Home键朝上")

   case.faceDown:

       print("设备处于平放,Home键朝下")

   case.unknown:

       print("设备屏幕方向未知")

   }

}

上一篇下一篇

猜你喜欢

热点阅读