最好的方法知道view的设置方向

需要检测当前View的设置方向。那个方法更好一点?

[[UIDevice currentDevice]orientation]

[[UIApplication sharedApplication] statusBarOrientation]

ChatGPT尝试为您解答,仅供参考
在 iOS 13 及更高版本中,建议使用以下方法来检测视图控制器的方向:

let currentOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation

这将返回当前视图控制器的方向。


但是,如果你想要检测设备本身的方向,那么你可以使用以下方法之一:

  • [[UIDevice currentDevice] orientation]

  • [[UIApplication sharedApplication] statusBarOrientation]

但是,在 iOS 13 及更高版本中,建议使用以下方法来检测设备的方向:

let currentOrientation = UIDevice.current.orientation

这将返回当前设备的方向。


需要注意的是,这些方法可能不会立即返回最新的方向信息。如果你希望在方向改变时收到通知,可以注册 UIDeviceOrientationDidChangeNotification 通知。

例如:

NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceOrientationChange), name: UIDevice.orientationDidChangeNotification, object: nil)

然后,你就可以在 handleDeviceOrientationChange 方法中处理方向改变了。