Alternative iOS layouts for portrait and landscape using just one .xib file

后端 未结 8 2138
清歌不尽
清歌不尽 2020-11-29 17:58

Using interface builder in xcode and just one .xib file, how can I create alternate layouts when rotating between landscape and portrait orientations?

See di

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 18:23

    Solution with storyboard [ios7]. Inside the main view controller, there is the container view that can include the tab bar controller. Inside the tab bar controller, there are 2 tabs. One tab is for controller with portrait and another is for controller in landscape mode.

    The main view controller implements these functions:

    #define INTERFACE_ORIENTATION() ([[UIApplication sharedApplication]statusBarOrientation])
    
    @interface MainViewController ()
    @property(nonatomic,weak) UITabBarController *embeddedTabBarController;
    @end
    
    @implementation MainViewController
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([segue.identifier isEqualToString:@"embedContainer"])
        {
            self.embeddedTabBarController = segue.destinationViewController;
            [self.embeddedTabBarController.tabBar setHidden:YES];
        }
    }
    
    - (void) adaptToOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        if (UIInterfaceOrientationIsLandscape(interfaceOrientation))
        {
            [self.embeddedTabBarController setSelectedIndex:1];
        }
        else
        {
            [self.embeddedTabBarController setSelectedIndex:0];
        }
    }
    - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
    {
        [self adaptToOrientation:interfaceOrientation];    
    }
    
    - (void) viewWillAppear:(BOOL)animated
    {
        [self adaptToOrientation:INTERFACE_ORIENTATION()];
    }
    

    The segue link in storyboard should be named "embedContainer".

    Assure that container view is resizable to fulfil the parent view, in both cases, landscape and portrait.

    Take care about the fact that in the runtime 2 instances of the same controller lives in the same time.

    Storyboard


    Update: Apple docs for alternate landscape view controller

提交回复
热议问题