在iOS上强制设备旋转问题

时间:2018-12-15 08:43:19

标签: ios swift

我正在尝试仅拍摄风景的一个视图,而其他所有视图都在肖像上。它可以工作,但是每个第二次屏幕上都根本没有旋转问题。

这是我正在谈论的场景: enter image description here

每隔2秒钟,设备旋转将不起作用。

这是我的代码

AppDelegate.swift

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

Controller1.swift

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

override var shouldAutorotate: Bool {
    return true
}

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

DetailController.swift

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    AppUtility.lockOrientation(.landscape, andRotateTo: .landscapeLeft)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    if isMovingFromParentViewController {
        AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
    }
}

Code that effects the rotation

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

}

那么,如何在每次加载时强制旋转细节视图?

1 个答案:

答案 0 :(得分:2)

步骤1:-请在应用程序委托中定义以下变量。

var shouldRotate : Bool = false

步骤2:-实施如下的委托方法。

//MARK:- Set Device Orientation Delegate Method

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return shouldRotate ? .landscapeRight : .portrait
}

第3步:-定义常量类,并在该类中添加“设置肖像方向”和“设置横向右方向”功能。

//MARK:- Set Portrait Orientation
func setPortraitOrientation() {
    appDelegateInstance.shouldRotate = false
    UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
}

//MARK:- Set Landscape Right Orientation

func setLandscapeRightOrientation() {
   appDelegateInstance.shouldRotate = true
   UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
}

步骤4:-在您的课程(目标景观课程)中使用以下代码

步骤4.1:-在视图中将显示如下所示的呼叫集“横向右对齐”功能。

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    setLandscapeRightOrientation()
 }

步骤4.2:-当您离开屏幕时,请在操作中执行以下代码。

//MARK:- Left Bar Button Tapped Delegate Method

func leftBarButtonTapped() {
    _ = self.navigationController?.popViewController(animated: false)
    setPortraitOrientation()
}

快乐编码!干杯!