Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 342
DanM Avatar asked Feb 06 '13 20:02

DanM


1 Answers

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];
like image 160
railwayparade Avatar answered Nov 01 '22 05:11

railwayparade