Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've defined a custom view in a NIB file and would like to instantiate a copy in a StoryBoard but I'm having issues with autolayout.

In a simple example, the custom view has single label with a fixed size and centered both vertically and horizontally, all using autolayout.

enter image description here

The file owner is set to my class, it has an outlet to the top view. In the custom view implementation I do:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [[NSBundle mainBundle] loadNibNamed:@"FMCompassView" owner:self options:nil];
        [self addSubview:self.topView];
    }
    return self;
}

Now, in my storyboard, I add a UIView, set it's class to my custom class and layout it out sized and centered on my page, again using autolayout.

enter image description here

And my widget is positioned and size properly but it's content is not resized as illustrated below: enter image description here

I tried adding more constraints after loading from the NIB, something along the lines of:

UIView* subV = self.topView;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(subV);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[subV]|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:viewsDictionary]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subV]|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:viewsDictionary]];

But this causes invalid layout constraints.

Any ideas on how to get this to work?

Cheers!

share|improve this question
think I found why: the view created from loading the NIB needs to be told not to convert auto resizing mask to constraints, EVEN if the content of the NIB is actually created with autolayout enabled. So after loading the NIB and before adding it's top view to the custom view, I need to call: [self.topView setTranslatesAutoresizingMaskIntoConstraints:NO]; – mkrus Jun 16 at 8:13

1 Answer

up vote 0 down vote accepted

The view created from loading the NIB needs to be told not to convert auto resizing mask to constraints, EVEN if the content of the NIB is actually created with autolayout enabled.

So after loading the NIB and before adding it's top view to the custom view, I need to call:

[self.topView setTranslatesAutoresizingMaskIntoConstraints:NO];
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.