首页 > 解决方案 > 当我旋转设备并单击选项卡项时,打开页面的视图保持横向模式

问题描述

有人可以帮忙吗。我支持我的设备上的肖像模式。但是只有一个视图控制器可以使用横向模式。当我打开支持横向模式的视图控制器并单击 tabBar 项目时,设备返回纵向模式,但视图仍处于横向模式。

这些是我的 appDelegate 代码:

   //Orientation Variables
    var myOrientation: UIInterfaceOrientationMask = .portrait

   
    var orientationLock = UIInterfaceOrientationMask.portrait
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientationLock
       
    }

    struct AppUtility {
      static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
          delegate.orientationLock = orientation
        }
      }

      static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
      }
    }

这是我的景观支持 ViewController :

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        AppDelegate.AppUtility.lockOrientation(.allButUpsideDown)
       
    }

我也有右导航栏按钮。当用户点击按钮时,屏幕会转动我有两个旋转功能

//MARK: Rotate Device to right
    func rotateToLandsScapeDevice(){
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.orientationLock = .landscapeRight;
        appDelegate.orientationLock = .allButUpsideDown;
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        UIView.setAnimationsEnabled(true)
        buttonClicked = false
    }


    //MARK: Rotate Device to portrait
    func rotateToPotraitScapeDevice(){
        
      let appDelegate = UIApplication.shared.delegate as! AppDelegate
        
        appDelegate.orientationLock = .portrait;
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        UIView.setAnimationsEnabled(true)
        
        buttonClicked = true
    }

当视图消失时,我转向纵向模式:

 override func viewWillDisappear(_ animated: Bool) {
      super.viewWillDisappear(animated)

       AppDelegate.AppUtility.lockOrientation(.portrait)
        
        UIView.setAnimationsEnabled(true)
        
    
    }

当我点击它旋转纵向模式时,旋转工作正常。但是当我点击标签栏项目视图看起来像这样:

在此处输入图像描述 在此处输入图像描述

标签: swiftlandscape-portrait

解决方案


在我的 TabBarController 类中,我检测到用户何时单击项目。然后我改变设备旋转。

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
          
          appDelegate.orientationLock = .portrait;
          UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
          UIView.setAnimationsEnabled(true)
    }

推荐阅读