iOS: Auto Layout vs autoresizingMask - resizing whole view to fill?

14,203

To accomplish the same thing using constraints you need to set the leading, trailing, top and bottom space to the superview to 0. See below:

//load the ButtonGridViewController from a xib
[[NSBundle mainBundle] loadNibNamed:@"..." owner:self options:nil];

//get the view add it
[self.view addSubView:self.myGridView];

//turn off springs and struts
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];

//add constraints to fill parent view
NSArray *arr;

//horizontal constraints
arr = [NSLayoutConstraint constraintsWithVisualFormat:@"|[vw]|"
                                                options:0
                                                metrics:nil
                                              views:@{@"vw":self.myGridView}];
[self.view addConstraints:arr];

//vertical constraints
arr = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[vw]|"
                                                options:0
                                                metrics:nil
                                                  views:@{@"vw":self.myGridView}];
[self.view addConstraints:arr];
Share:
14,203
DanM
Author by

DanM

I'm a lead software systems engineer at a large government-funded nonprofit. My expertise is in web development, machine learning, visualization, iOS, and being generally delightful. #SOReadyToHelp

Updated on June 04, 2022

Comments

  • DanM
    DanM almost 2 years

    I've got a storyboard which is built using Auto Layout. Within that storyboard, I'm embedding a UIViewController subclass (ButtonGridViewController) in several locations, each of which is a different size. ButtonGridViewController's view is defined in a xib.

    What I need is for the entirety of the ButtonGridViewController's view to simply scale-to-fill the view I'm embedding it in. With the old struts-and-springs method, this was trivial -- just set all the subviews to resize in both directions, and voila, piece of cake.

    How do I accomplish the same thing using constraints? For what it's worth, the xib just contains a main view, which is rectangular, and has 4 subviews - each a button - arranged in a 2x2 grid. I want everything, including the buttons AND spacing, to scale and/or stretch to fill the view it's going into.

    Thanks!

  • Mayur Deshmukh
    Mayur Deshmukh almost 9 years
    Same thing is not working for me. I have same scenario where I am adding a subview to my view. View is in Storyboard and subview is in .xib. WHen I add constraints programmatically like above, I get simultaneous constraints and it breaks...