ios - 在不旋转视图的情况下检测 iOS 设备方向变化
问题描述
我有一个 UIViewController,我想检测该 ViewController 上的设备方向变化。但我不想旋转视图。我的应用程序支持所有方向,但这个 ViewController 应该一直保持纵向模式。
我只能设置supportedInterfaceOrientations
为纵向以获得所需的功能。但我仍然想知道这个 ViewController 中的方向变化。通常我可以使用viewWillTransition
方法或traitCollectionDidChange
方法来获取事件。但是当我设置supportedInterfaceOrientations
为肖像时,这些方法都没有被调用。
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
// this method never get called
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
当我仅设置为纵向时,有没有办法检测设备方向的变化?supportedInterfaceOrientations
解决方案
我认为您可以订阅通知
final class ViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, #selector(handleOrientationChange, name: UIDevice.orientationDidChangeNotification, object: nil))
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc
private func handleOrientationChange() {
// Yay, orientation changed!
}
}
推荐阅读
- excel - 使用 VBA 将 Powerpoint 图表标签提取到 Excel
- ios - 有什么方法可以在 iOS 上以编程方式检测死锁
- java - 如何实例化一个类对象?
- android - Lint 在组装发布目标时发现致命错误
- javascript - Grant vs PassportJS vs OAuth2-client-js 哪一个用于移动应用登录?
- c# - ImageResizer 磁盘缓存 System.IO.IOException
- angular - 对 Material datepicker 使用自定义标题,其中 Material version < 6 和 Angular version < 6
- php - 我想计算给定主题的总价格并将其存储在数据库中
- html - 创建滑块但在绝对 div 的中心拟合图像时遇到问题
- json - Powershell:获取原始 JSON 的值