如何在导航到UIViewController时将其旋转到支持的界面方向?

时间:2016-01-07 12:38:18

标签: ios cocoa-touch ios8 ios9

我有一个以纵向锁定的viewcontroller(带有子视图控制器),使用以下代码来实现此目的:

- (UIInterfaceOrientationMask) supportedInterfaceOrientations {
    if ([self.centerViewController respondsToSelector:@selector(supportedInterfaceOrientations)]) {
        return [self.centerViewController supportedInterfaceOrientations];
    }
    return UIInterfaceOrientationMaskAll;
}

这非常有效,如果我需要锁定该视图,我可以“覆盖”当前centerViewController中的supportedInterfaceOrientations,如果我希望视图支持所有内容,请将其保留。

问题是锁定的视图在导航时不会旋转到支持的方向。一个视图以纵向方式锁定,但在横向显示另一个视图并导航到此视图时,即使此视图不支持横向,也会以横向显示该视图。

如何在导航时确保视图旋转到允许的方向?

2 个答案:

答案 0 :(得分:0)

如果您在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) {
    }
}

答案 1 :(得分:0)

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];

希望我能解决你的问题。