我正在使用NotificationCenter
观察interfaceOrientation
随UIApplication.willChangeStatusBarOrientationNotification
的变化。但是UIApplication.willChangeStatusBarOrientationNotification
现在被标记为已弃用。建议使用viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
,但这是从ViewController
调用的方法。我有一个UIView
的子类,内部需要这个子类,而Im将这个View
公开为framework
。我希望仍然能够保持此功能,而无需从ViewController
中显式调用。是否有另一个选择可以直接在View
内部实现此目标?我尝试用KVO观察UIWindowScene.interfaceOrientation
,但这没有用。
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)
}
实际上,我不使用通知来观察方向变化,因为它对我不起作用。我将viewDidLayoutSubviews
用于如下操作。
class HomeViewController: UIViewController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
/* orientation change */
detectOrientation()
}
func detectOrientation() {
if UIDevice.current.orientation.isLandscape {
} else {
}
}
}