Anastasia
Anastasia

Reputation: 3034

Don't collapse UISplitViewController in horizontally compact environment

The default behaviour of UISplitViewController is that it collapses when it transitions from a horizontally regular to a horizontally compact environment. Is it possible to override this somehow?

I want the splitView to be always expanded due to some design solutions. I didn't find the solution in the documentation on the UISplitViewController: the property collapsed is readonly, and delegate methods are intended only for "how to collapse", but not for "don't collapse at all". I'm using iOS9 SDK.

Upvotes: 3

Views: 699

Answers (1)

Anastasia
Anastasia

Reputation: 3034

I figured it out. Docs states:

The split view controller determines the arrangement of its child view controllers based on the available space. In a horizontally regular environment, the split view controller presents its view controllers side-by-side whenever possible. In a horizontally compact environment, the split view controller acts more like a navigation controller, displaying the primary view controller initially and pushing or popping the secondary view controller as needed.

So the splitView will always be collapsed in Compact horizontal environment and expanded in Regular. The solution is to tell the splitView that it has Regular horizontal environment when we want it to be expanded. The idea is taken from WWDC 2014 Video "Building Adaptive Apps with UIKit". Unfortunately, the sample code they mention in the Video doesn't cover this case. But the idea is to create containing ViewController for the SplitViewController, where we can override trait collection of the SplitViewController using method setOverrideTraitCollection:forChildViewController:

@implementation ContainingViewController

- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nil bundle:nil];
    if (self)
    {
        _splitViewController = [[UISplitViewController alloc] initWithNibName:nil bundle:nil];
        _splitViewController.viewControllers = <view controllers>;

        [self addChildViewController:_splitViewController];
        [self.view addSubview:_splitViewController.view];

        UITraitCollection *horizontallyRegularTraitCollection = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular];
        [self setOverrideTraitCollection:horizontallyRegularTraitCollection forChildViewController:_splitViewController];
    }
    return self;
}

With this code, SplitViewController will always have Regular horizontal trait collection, and thus expanded.

Upvotes: 1

Related Questions