代码之家  ›  专栏  ›  技术社区  ›  Krunal Nagvadia

swift:使用pushviewcontroller更改方向

  •  1
  • Krunal Nagvadia  · 技术社区  · 6 年前

    当视图从一个视图控制器推送到另一个视图控制器时,我想更改视图的方向。就像当它推动它时,它应该变成横向的肖像。

    我试着编写这段代码,但没有正常工作。

    ViewDidLoad

    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(UIInterfaceOrientationMask.landscapeRight, andRotateTo: UIInterfaceOrientation.landscapeRight)
        }
    

    但它不会改变方向。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Ben Rockey    6 年前

    应用内委派

    import UIKit
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    @UIApplicationMain
    
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        var deviceOrientation = UIInterfaceOrientationMask.portrait
        func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
            return deviceOrientation
        }
    }
    

    在uiviewcontroller中

    override func viewWillAppear(_ animated: Bool) {
            appDelegate.deviceOrientation = .landscapeLeft
            let value = UIInterfaceOrientation.landscapeLeft.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        }
    
        2
  •  0
  •   Vishal Patel    6 年前

    我已经实现了相同的代码并得到了相同的问题,所以我在调用“lockorientation”并解决它之前添加了下面的代码。

    UIDevice.current.setValue(UIInterfaceOrientationMask.landscapeRight.rawValue, forKey: "orientation")
    UIViewController.attemptRotationToDeviceOrientation()
    
    推荐文章