software-mariodiana
2/28/2017 - 8:18 PM

How to create a custom UIView whose frame will expand to fill the entire frame of its parent view.

How to create a custom UIView whose frame will expand to fill the entire frame of its parent view.

@implementation ExpandingView

- (BOOL)requiresConstraintBasedLayout
{
    return YES;
}

- (void)didMoveToSuperview
{
    // We override -didMoveToSuperview to setup our constraints with our parent view.
    UIView* superview = [self superview];
    
    if (superview == nil) {
        // This method gets called when a view is removed from a superview, so be careful!
        return;
    }
    
    self.translatesAutoresizingMaskIntoConstraints = NO;
    
    [[self topAnchor] constraintEqualToAnchor:[superview topAnchor]].active = YES;
    [[self leadingAnchor] constraintEqualToAnchor:[superview leadingAnchor]].active = YES;
    [[self trailingAnchor] constraintEqualToAnchor:[superview trailingAnchor]].active = YES;
    [[self bottomAnchor] constraintEqualToAnchor:[superview bottomAnchor]].active = YES;
    
    [superview setNeedsLayout];
}

@end