Disable rotation for one UITabbar item

房东的猫 提交于 2019-12-11 03:20:46

问题


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


来源:https://stackoverflow.com/questions/21886900/disable-rotation-for-one-uitabbar-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!