简体   繁体   English

在没有旋转视图的情况下检测 iOS 设备方向变化

[英]Detect iOS device orientation change without rotating view

I have a UIViewController and I wanna detect the device orientation changes on that ViewController.我有一个 UIViewController,我想检测该 ViewController 上的设备方向变化。 But I do not want to rotate the view.但我不想旋转视图。 My app supports all orientations but this ViewController should keep portrait mode all the time.我的应用程序支持所有方向,但此 ViewController 应始终保持纵向模式。

I can set supportedInterfaceOrientations to portrait only to get the desired functionality.我可以将supportedInterfaceOrientations设置为 portrait only 以获得所需的功能。 But I still wanna know the orientation changes within this ViewController.但我仍然想知道这个 ViewController 中的方向变化。 Normally I can get the event with the viewWillTransition method or traitCollectionDidChange method.通常我可以使用viewWillTransition方法或traitCollectionDidChange方法获取事件。 But when I set supportedInterfaceOrientations to portrait none of those methods get called.但是当我将supportedInterfaceOrientations设置为 portrait 时,这些方法都不会被调用。

    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)
    }

Is there a way to detect the device orientation changes when I set supportedInterfaceOrientations to portrait only?当我将supportedInterfaceOrientations设置为仅纵向时,有没有办法检测设备方向的变化?

I think you can subscribe to a notification我想你可以订阅通知

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!
    }
}

Heres one way to do it.这是一种方法。

        
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
          //  return UIInterfaceOrientationMask.all } else{ }
        return self.orientationLock
    }

Then for viewController you want to change the desired orientation allowed然后对于 viewController,您要更改允许的所需方向

   AppDelegate.AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM