beginGeneratingDeviceOrientationNotifications如何工作

时间:2013-04-14 07:08:59

标签: ios objective-c

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [notificationCenter addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
    orientation = AVCaptureVideoOrientationPortrait;

我想知道beginGeneratingDeviceOrientationNotifications意味着什么以及如何工作?

3 个答案:

答案 0 :(得分:24)

当你写这一行时:

 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

您对设备说:“每次更改方向时都请通知应用程序”

写下这个:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];

您对该应用程序说:“每次收到更改方向通知时,请致电deviceOrientationDidChange方法。”

现在在deviceOrientationDidChange您可以执行以下操作:

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait)
     [self doSomething];
else
     [self doSomethingElse];

答案 1 :(得分:4)

Swift 4.2

class ViewController: UIViewController {

     override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @objc func deviceOrientationDidChange() {
        print(UIDevice.current.orientation.rawValue)
    }
}

Swift 3.0

我希望有人能够迅速写出来。我知道这是一个Obj-C帖子,但是我找不到像这样的快捷帖子,所以你走了:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

    }

    deinit {
         NotificationCenter.default.removeObserver(self)
    }

    func deviceOrientationDidChange() {
        print(UIDevice.current.orientation.rawValue)
    }

}

答案 2 :(得分:2)

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

这是获取通知的可选项。 如果有人知道它是如何工作的,请分享。