What happens with constraints when a view is removed What happens with constraints when a view is removed ios ios

What happens with constraints when a view is removed


The constraints are removed. If you add A again, you will have to make new constraints for it, or if you save the constraints before you remove A, you can add them back. When I do something like this, I save the constraints like this for a view called view1:

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


Since I had this question too, I checked the Apple Docs just for kicks, and it turns out that it is documented that the constraints are removed.

The documentation for the UIView removeFromSuperview method states:

Calling this method removes any constraints that refer to the view you are removing, or that refer to any view in the subtree of the view you are removing.

I'm not sure if this was documented last year when the original question was posted, but I just thought I'd share this information in case anyone needed it...


Be aware though, that if you have two independent parent views A and B, and a subview C, where C is currently a subview of A, with appropriate constraints, that calling [B addSubview:C] will NOT clear any constraints relating to A and C, and auto layout will start throwing exceptions, because those constraints no longer relate to views in the same hierarchy.

You will need to call [C removeFromSuperview] explicitly to remove the constraints, before adding C to B.

This is true on Mac OS X - I haven't checked iOS