Disable rotation for one UITabbar item

2019-07-23 17:53发布

问题:

I have a uitabbarcontroller with 4 tab bar items and each tab bar item has a uinavigationcontroller.

I needed to lock the orientation of one uitabbar item only to Portrait. So i implemented the following code:

Created a custom tab bar controller and added the following code in it:

MainTabBarController.m

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // You do not need this method if you are not supporting earlier iOS Versions
    return [self.selectedViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}

-(NSUInteger)supportedInterfaceOrientations
{
    if (self.selectedViewController)
        return [self.selectedViewController supportedInterfaceOrientations];

    return UIInterfaceOrientationMaskPortrait;
}

-(BOOL)shouldAutorotate
{
    return YES;
}

Created a custom navigation controller to use in one of the uitabbaritems and added the following code in it:

-(NSUInteger)supportedInterfaceOrientations
{
    return [self.topViewController supportedInterfaceOrientations];
}

-(BOOL)shouldAutorotate
{
    return YES;
}

and for the uiviewcontroller in the custom navigation controller i added the following code:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

The above code works fine. My issue is, if you go to the tabbar item (whose orientation is locked to Protrait) when the device is already in Landscape mode the orientation changes to Landscape. Can anyone please help me how to solve my issue.

Thanks, Anand.

回答1:

FYI!!! I've found a way for my problem. I added the following function to the viewcontroller for which i want the display only in protrait mode:

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation]))
    {
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
        {
            int orientationPortrait = UIInterfaceOrientationPortrait;
            NSMethodSignature *sig = [[UIDevice currentDevice] methodSignatureForSelector:@selector(setOrientation:)];
            NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig];
            [invo setTarget:[UIDevice currentDevice]];
            [invo setSelector:@selector(setOrientation:)];
            [invo setArgument:&orientationPortrait atIndex:2];
            [invo invoke];
        }
    }
}