如何在导航到UIViewController时将其旋转到支持的界面方向?
我有一个viewcontroller(与儿童viewcontrollers)被locking在肖像,使用下面的代码来完成这一点:
- (UIInterfaceOrientationMask) supportedInterfaceOrientations { if ([self.centerViewController respondsToSelector:@selector(supportedInterfaceOrientations)]) { return [self.centerViewController supportedInterfaceOrientations]; } return UIInterfaceOrientationMaskAll; }
这完美的作品,我可以“重写”我的当前centerViewController supportedInterfaceOrientations如果我需要locking该视图,并保留它,如果我希望视图支持一切。
问题是被locking的视图在导航时不会旋转到支持的方向。 一个视图被locking在肖像中,但是当在景观中显示另一个视图并导航到这个视图时,它会以横向显示,即使这个视图不支持景观。
如何确保在浏览时将视图旋转到允许的方向?
如果您在supportedInterfaceOrientations
返回了支持的方向,我将自动旋转。
#pragma mark - Orientation Handling - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (BOOL)shouldAutorotate {// iOS 6 autorotation fix return YES; } - (UIInterfaceOrientationMask)supportedInterfaceOrientations {// iOS 6 autorotation fix return UIInterfaceOrientationMaskLandscapeLeft; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {// iOS 6 autorotation fix return UIInterfaceOrientationPortrait; } - (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { } }
在AppDelegate.h
添加以下属性
@property (readwrite) BOOL restrictRotation;
在AppDelegate.m
添加以下代码
-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if(self.restrictRotation) return UIInterfaceOrientationMaskLandscape; else return UIInterfaceOrientationMaskPortrait; }
在你想要限制方向的ViewController.m中添加以下代码:
-(BOOL)shouldAutorotate { return NO; } -(void) restrictRotation:(BOOL) restriction { AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate; appDelegate.restrictRotation = restriction; } - (NSUInteger) supportedInterfaceOrientations { // Return a bitmask of supported orientations. If you need more, // use bitwise or (see the commented return). return UIInterfaceOrientationMaskLandscape; // return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { // (iOS 6) // Prefer (force) landscape return UIInterfaceOrientationLandscapeRight; }
另外,当你离开你的Landscape ViewController.m时,进行下面的函数调用
[self restrictRotation:NO];
希望我能解决你的问题。