how to lock portrait orientation for only main view using swift

后端 未结 16 1914
野性不改
野性不改 2020-12-07 13:38

I have created an application for iPhone, using swift, that is composed from many views embedded in a navigation controller. I would like to lock the main v

16条回答
  •  悲&欢浪女
    2020-12-07 14:12

    You do have to apply this to your top view controller. However, you can do it in a clean/easy way by subclassing your top view controller and setting a variable within it that to references every time you make a call to:

    shouldAutoRotate()
    

    which is called when the device detects an orientation change and precedes the call to:

    supportedInterfaceOrientations()//this is only called if shouldAutoRotate() returns true
    

    For example, say my top view controller is a TabBarController:

    class SomeSubclassTabBarViewController: UITabBarController { //This subclass allows us to pass along data to each of the tabBars
    
    var dataArray = StoredValues()//also useful for passing info between tabs
    var shouldRotate: Bool = false
    
    
    override func shouldAutorotate() -> Bool { //allow the subviews accessing the tabBarController to set whether they should rotate or not
        return self.shouldRotate
    }
    

    }

    Then within the view which should have the ability to rotate the screen, set the viewWillAppear() and viewWillDisappear() like so:

    override func viewWillAppear(animated: Bool) { //set the rotate capability to true
        let sharedTabBarController = self.tabBarController as SomeSubclassTabBarViewController
        sharedTabBarController.shouldRotate = true
    }
    
    override func viewWillDisappear(animated: Bool) {
        let sharedTabBarController = self.tabBarController as SomeSubclassTabBarViewController
        sharedTabBarController.shouldRotate = false
    }
    

    and just in case your app crashes while on this screen, it's probably a good idea to explicitly set the shouldRotate: Bool value on each of your views within the viewWillLoad() method.

提交回复
热议问题