ORStudios ORStudios - 1 month ago 16
Objective-C Question

How do I programatically assign a UIViews Autolayout edges to match the superview?

I have a modal view that I am adding to the ViewController, now traditionally I have always just resized based on the screen size so that the background of the modal covers the entire screen and has a slight alpha to allow the content to be seen through.

With my current app I am allowing the user to change the orientation so the above method does not work. I was trying to find a way programmatically to assign all the autolayout edges of the modal to 0 in relation to self.view. I have tried the following code but am getting errors.

[self.view addSubview:self.viewPromptSignup];

self.viewPromptSignup.translatesAutoresizingMaskIntoConstraints = NO;

/* pin Left of child to left of parent */
[self.viewPromptSignup addConstraint:[NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.viewPromptSignup
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0]];

/* pin Right of child to right of parent */
[self.viewPromptSignup addConstraint:[NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.viewPromptSignup
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0]];

/* pin top of child to bottom of nav bar(or status bar if no nav bar) */
[self.viewPromptSignup addConstraint:[NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.viewPromptSignup
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0]];

/* pin Top of nav bar to bottom of child view */
[self.viewPromptSignup addConstraint:[NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.viewPromptSignup
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0]];

Answer

You can use Masonry library because it's super easy to add constraints.

Check it out https://github.com/SnapKit/Masonry

And using this library you can easily set the constraints like this:

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(superview.mas_top);
    make.left.equalTo(superview.mas_left);
    make.bottom.equalTo(superview.mas_bottom);
    make.right.equalTo(superview.mas_right);
}];

It's super easy