1

NotificationCenter用来观察interfaceOrientation变化UIApplication.willChangeStatusBarOrientationNotification。但UIApplication.willChangeStatusBarOrientationNotification现在标记为已弃用。建议使用viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator,但这是从 中调用的方法ViewController。我有一个UIView内部需要它的子类,我将它暴露Viewframework. 我希望能够仍然保持此功能,而无需从ViewController. 是否有另一种选择可以直接在内部实现这一目标View?我尝试UIWindowScene.interfaceOrientation使用 KVO 进行观察,但这不起作用。

public extension Notification.Name {
    static let willChangeStatusBarOrientationNotification = UIApplication.willChangeStatusBarOrientationNotification    
}

...

@objc private func statusBarOrientationWillChange(notification: Notification) {
    if let orientationRawValue = notification.userInfo?[UIApplication.statusBarOrientationUserInfoKey] as? Int, let orientation = AVCaptureVideoOrientation(rawValue: orientationRawValue) {
        configureVideoOrientation(interfaceOrientation: orientation)
        updateSceneInformation()
    }
}

...

private func initialize() {
    NotificationCenter.default.addObserver(self, selector: #selector(statusBarOrientationWillChange(notification:)), name: .willChangeStatusBarOrientationNotification, object: nil)

}

在此处输入图像描述

4

1 回答 1

0

尝试这个。它似乎只能用作方向更改后通知,而不是方向更改前通知,但它不应产生弃用警告。请注意,设备方向是UIDeviceOrientation类型,而不是UIInterfaceOrientation类型。

public class MyView: UIView {

    public override init(frame: CGRect) {
        super.init(frame: frame)
        NotificationCenter.default.
                addObserver(self, 
                            selector: #selector(deviceOrientationDidChange), 
                            name: UIDevice.orientationDidChangeNotification, 
                            object: nil)
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    @objc
    private func deviceOrientationDidChange(_ notification: Notification) {
        guard UIDevice.current.orientation.isValidInterfaceOrientation,
              let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.current.orientation.rawValue) 
            else { return }
        configureVideoOrientation(interfaceOrientation: orientation)
        updateSceneInformation()
    }

}
于 2019-12-19T17:55:57.103 回答