Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the autolayout constraints affecting a given subview?

As much as I love autolayout as a concept, I seem to be constantly tripping over implementation details. One of those is that I'm getting really tired of storing constraints that are applied to a given subview so I can remove and replace them later.

For example, when I first add a view, I might given it the constraint:

@"H:[view(==200)]|"

To lay it out against the right hand side of the screen, with a width of 200. What if I later want to make it 400 wide, with a 200 sized gap? The new layout is simple enough, but directly contradicts the old one:

@"H:[view(==200)]-(200)]|"

So I have to hold arrays of constraints, so I can later use them to remove said constraints. There has got to be a simpler solution that I'm missing somewhere. Unfortunately, the obvious solution of [view constraints] doesn't make sense, because you don't apply constraints directly to a given view, you apply them to it's superview. (Plus, it tends to be filled with the autolayout constraints that make it's own objects fit properly -- not stuff you want to remove just to adjust it's position!) And there doesn't appear to be any [view constraintsForSubview:] option available.

Am I blind? Missing something? Do I really need to hand around dictionaries of existing constraints so I can fix them later?

like image 445
RonLugge Avatar asked Sep 18 '13 00:09

RonLugge


1 Answers

You can make IBOutlets to the constraints and change the constant parameter in code. So, if what you're trying to do is like your example, you can do it like this (calling the width constraint widthCon):

self.widthCon.constant = 400;

This would leave the constraint to the right side at 200 (you could make an outlet to that one too if you want to change that one).

If you do want to save (or delete) constraint fo a certain view, you can use a method similar to this:

for (NSLayoutConstraint *con in self.view.constraints) {
        if (con.firstItem == self.leftButton || con.secondItem == self.leftButton) {
            [self.portraitConstraints addObject:con];
        }
    }

Of course, you could create a category on UIView that would use something like that to make a viewConstraintsForView: method.

like image 106
rdelmar Avatar answered Sep 28 '22 02:09

rdelmar