关于监听与控制设备旋转全解析(UIDeviceOrientationDidChangeNotification)

一类情况:

  初始化app的方向,比如只支持横屏或者竖屏。下面举例只支持竖屏的案例

在app的属性里面手动设置

 

上面标注了该app支持的方向种类,要是在app里支持Portrait方向,还需要添加以下代码

二类情况:

上面的代码表明app支持了两个方向,Protrait 和PortraitUpsideDown,如果我要求在app在某个

方向的时候禁止屏幕旋转,该怎么做呢?

在swift中禁止当前屏幕旋转

       UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications()
        UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications()

 注意是两行,理论上只要一行代码,但是可能是swift中的bug,笔者发现连续调用两次才能达到

禁止屏幕旋转的效果

打开屏幕旋转:

UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()

 这里只要一行就可以打开屏幕旋转的功能了,😄

三类情况:

我们在控制了屏幕怎么旋转之后该怎么监听这些旋转的事件呢?因为我们往往需要在屏幕旋转的时候做

一些我们需要的操作。

在初始化的时候添加事件监听:

    override func viewWillAppear(animated: Bool) {
             NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)
    }

在deviceOrientChange中就可以任意的写自己需要的功能了

在UI删除的时候一定要记得删除监听

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil)

 

 注意:

  如果某个UI监听了Notification的事件,在将这个对象在superView中删除的时候务必在之前注销这个监听,否则会崩溃程序

可以添加析构函数:

 


 

posted @ 2015-03-17 15:17  流火行者  阅读(2094)  评论(0编辑  收藏  举报