Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens with constraints when a view is removed

People also ask

What happens to constraints when a view is hidden?

Normally, hiding a view (by setting isHidden ) has no effect on layout. Hidden views participate in layout. Any constraints connected to the view are still enforced. The area occupied by the now-hidden view is still reserved for it.

Does removing from superview remove constraints?

If the view's superview is not nil , the superview releases the view. 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.


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


The constraints are also removed when you [A removeFromSuperview]

They are forgotten and adding A to C again adds no constraints.