MKodes
MKodes

Reputation: 81

Custom child view does not fit parent

I have a view setup in XIB linked to a viewController, all of the views within XIB have the expected layout. However, some of the views will have to be initialised in code hence I added them as subviews such that:

//Setup first custom view
FirstCustomView *firstCustomView = [[FirstCustomView alloc] initWithFrame: self.firstView.frame withDelegate:self];
 //where self.firstView is a UIView
[self.firstView addSubview: firstCustomView];

//Setup second custom view
SecondCustomView *secondCustomView = [[[NSBundle mainBundle] loadNibNamed:@"SecondCustomView" owner:nil options:nil] firstObject];
 //where self.secondView is a UIView
[self.secondView addSubview: secondCustomView];

As you can see some view's are initialised from XIBs and some are initialised with frames. Either way I am having the same problem where the subviews don't fill the parent view. Any tips?

Upvotes: 1

Views: 244

Answers (1)

skaak
skaak

Reputation: 3018

Some code I use for that kind of stuff ...

// Given a parent view, embed a child view in it so that the child spans the full parent
+ ( void ) embed:( UIView * ) child
        into:( UIView * ) parent
{
    [parent addSubview:child];
    
    [child.topAnchor    constraintEqualToAnchor:parent.topAnchor].active    = YES;
    [child.rightAnchor  constraintEqualToAnchor:parent.rightAnchor].active  = YES;
    [child.leftAnchor   constraintEqualToAnchor:parent.leftAnchor].active   = YES;
    [child.bottomAnchor constraintEqualToAnchor:parent.bottomAnchor].active = YES;
}

Upvotes: 1

Related Questions