How do I get the autolayout constraints affecting a given subview?
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.
Related videos on Youtube
RonLugge
Updated on September 15, 2022Comments
-
RonLugge over 1 year
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?
-
RonLugge over 10 yearsThanks. Unfortunately that was a deliberately contrived example, so going in and modifying them in the manner you stated might not be the best choice (though I'll definitely keep it in mind), but that quick 'function' you came up with looks like something I"ll probably be adding to a lot of my VCs.