Make Interface Builder draw IB_DESIGNABLE subviews with the currently selected size class

334 Views Asked by At

I have a XIB (file's owner: DesignableView) that I laid out in Interface Builder in two different size classes:


DesignableView.xib: Any | Any

Designable View.xib: Any | Any


DesignableView.xib: Regular | Any

Designable View.xib: Regular | Any


I want to use this DesignableView inside another XIB file. As I am a huge WYSIWYG fan I made the view IB_DESIGNABLE and added the following code to the file's owner class:

DesignableView.h

IB_DESIGNABLE
@interface DesignableView : UIView

@end

DesignableView.m

@implementation DesignableView

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self loadNib];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self loadNib];
    }
    return self;
}

- (void)loadNib
{
    NSString *nibName = NSStringFromClass(self.class);
    NSBundle *bundle = [NSBundle bundleForClass:self.class];
    UINib *nib = [UINib nibWithNibName:nibName bundle:bundle];
    UIView *view = [nib instantiateWithOwner:self options:nil][0];
    view.frame = self.bounds;
    view.layoutMargins = self.layoutMargins;
    [self addSubview:view];
}

@end

All this code does is rendering the view wherever I use it in Interface Builder.

Now I create another XIB file and set its file's owner to ContainerView. I add two empty UIViews to it and set their class property to DesignableView. Interface Builder updates the views after a few seconds and shows the two DesignableViews as laid out in the first XIB - just as expected.

However, it always loads the layout specified in the "Any | Any" size class of DesignableView - regardless of ContainerView's size class (see screenshots below).


ContainerView.xib: Any | Any

Container View.xib: Any | Any


ContainerView.xib: Regular | Any

Container View.xib: Regular | Any


(At runtime the DesignableView always appears with the correct size class layout.)

Is there any way to make Interface Builder display IB_DESIGNABLE views in the correct size class?

i.e. the wanted behavior is:

while editing ContainerView.xib in Interface Builder

↓

switch size class (e.g. to Regular | Any)

↓

Interface Builder draws subviews with class `DesignableView` 
with the respective size class (Regular | Any)
0

There are 0 best solutions below