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

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

4

3 回答 3

26

当您编写此行时:

 [[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];
于 2013-04-14T07:41:41.413 回答
8

斯威夫特 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)
    }
}

斯威夫特 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)
    }

}
于 2017-02-06T01:44:10.240 回答
2
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

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

于 2015-12-12T11:42:09.267 回答