Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - Force autorotation

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?

like image 318
Bogdan Bogdanov Avatar asked Dec 20 '16 00:12

Bogdan Bogdanov


1 Answers

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]
    }
}
like image 148
ronan Avatar answered Oct 04 '22 01:10

ronan