iOS8 - prevent rotation on presenting viewControll

2020-02-25 23:45发布

问题:

We have a MainViewController with a tableView, and it presents a new modalViewController.

The MainViewController is restricted to portrait only, and the modalViewController can rotate.

The problem is in iOS8, that when the modalViewController rotates, the callback method of rotation in iOS8 in MainViewcontroller is called - - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator

Thus, the UITableView is getting its data reloaded, which is a behaviour we don't want.

Can we prevent this feature of iOS 8, and not rotate the presenting UIViewController?

回答1:

So after long days of searching and investigating, I finally came up with a possible solution.

First of all, I can use navigation controller and push the viewController instead of presenting it, but it breaks my code and just isn't so true.

The second thing I can do is not setting constraints. I still can use autolayout, but if I don't set constraints, and let the default constraints to be set, the tableView doesn't get reloaded. of course this is also isn't very smart thing to do, as I have many elements in my viewController.

Finally, I figured out that I can show this "modal" viewController in another UIWindow. I create UIWindow and set the modalViewController as its rootViewController.

I put some example project in git: https://github.com/OrenRosen/ModalInWindow

Hope it will be helpful.



回答2:

I did something similar with a navigation controller, that wouldn't rotate unless the top pushed controller does rotate.

In your case check if the main controller is presenting another controller. If it isn't then just reject rotation, otherwise return whatever the presented controller returns for the rotation method.

As for your table view, it shouldn't get reloaded because of rotations.



回答3:

In iOS 8 the view that rotates when you change the device orientation is the first view added to the UIWindow. So, if you save a reference to it in your presentedController, you can overwrite the shouldAutorotate and supportedInterfaceOrientations values.