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

后端 未结 8 2131
清歌不尽
清歌不尽 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:05

    Resize Programatically

    I have an app where I have exactly the same situation. In my NIB I just haven the portrait layout. The other layout is performed programatically. It is not that difficult to specify a few sizes programmatically, so no need to maintain two NIBs.

    Note that performing the view change programatically by setting frames will result in an animation (or can easily be made using an animation). This will give the user a valuable feedback about which component moved to which position. If you just load a second view, you will lose this advantage and from a UI perspective I believe loading an alternative view is not a good solution.

    Use two ViewControllers

    If you like to use two ViewControllers, then Apple describes how to do it in its developer documentation, i.e., you find the answer to you question here: RespondingtoDeviceOrientationChanges.

    If you like to do it programatically you may add re-position code in the method didRotateFromInterfaceOrientation.

    Example

    I added the method to my ViewController:

    - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
    {
        [self adjustLayoutToOrientation];
    }
    

    Then implemented the adjustment of the layout. Here is an example (the code is specific to my app, but you can read sizes of superviews and calculate frames of subviews from it.

    - (void)adjustLayoutToOrientation
    {
        UIInterfaceOrientation toInterfaceOrientation = self.interfaceOrientation;
        bool isIPhone = !([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad);
    
        [self adjustViewHeight];
        [self adjustSubviewsToFrame: [mailTemplateBody.superview.superview frame]];
    
        CGRect pickerViewWrapperFrame = pickerViewWrapper.frame;
        if(isIPhone) {
            pickerViewWrapperFrame.origin.x = 0;
            pickerViewWrapperFrame.size.height = keyboardHeight;
            pickerViewWrapperFrame.origin.y = [self view].frame.size.height-pickerViewWrapperFrame.size.height;
            pickerViewWrapperFrame.size.width = [self view].frame.size.width;
        }
        else {
            pickerViewWrapperFrame = pickerView.frame;
        }
    
    // MORE ADJUSTMENTS HERE
    
    }
    

提交回复
热议问题