Swift 3 - Force autorotation
Asked Answered
L

1

5

I am using this code.

For example, I have view1 (portrait only) and view2 (portrait+landscape). When you are in view1 and click a button, you open view2 with popup on the whole screen. When you close view2 and view1 become visible, I want to automatically turn it to portrait mode, if view 2 was in landscape. Any suggestions?

Lagasse answered 20/12, 2016 at 0:26 Comment(2)
The answer already existed : How to lock specific view controller with specific orientationMiddleoftheroad
changing into swift 3 isn't difficult.Middleoftheroad
O
13

As you've said you were using popup, I'm sure you're using a navigationController. here's the view hierarchy.

There are three viewControllers corresponds to those xib.

The viewController is set to portrait only, and the secondViewController is set to portrait and landScapeLeft(you can change it to whatever you need). It works just fine as you required. When the second one is in landscape, pop to the first, it will be forced to set to portrait.

NavViewController

ViewController

SecondViewController

views hierarchy

//NavViewController.swift

class NavViewController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override var shouldAutorotate: Bool {
        return (visibleViewController?.shouldAutorotate)!
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return (visibleViewController?.supportedInterfaceOrientations)!
    }
}

//ViewController.swift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override var shouldAutorotate: Bool {
        return false
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let value =  UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    }
}

SecondViewController.swift class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.portrait, .landscapeLeft]
    }
}
Overabundance answered 20/12, 2016 at 3:29 Comment(2)
I needed only ` let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") UIViewController.attemptRotationToDeviceOrientation()` thanks :)Lagasse
Bogdan Bogdanov me too :pUnquiet

© 2022 - 2024 — McMap. All rights reserved.