DerrickHo328
DerrickHo328

Reputation: 4886

How to Uninstall a UIView programmatically

In Interface builder the power of size classes lets you install constraints or uninstall them. In code you can do something similar by toggling the active property.

Interface Builder also lets you install or uninstall views. However, I would like to be able to do this programatically. UIView doesn't appear to have an active property. Is there any way I can uninstall a view programmatically? I'm looking for something where I can simply toggle a boolean property and the view and its constraints go into a dormant state and the view is no longer visible ands its constraints are no longer constraining until it is toggled to be non-dormant and then the view and the constraints work again.

Is this possible? Any workarounds?

Upvotes: 4

Views: 2060

Answers (1)

Kurt Anderson
Kurt Anderson

Reputation: 932

A view's hidden property does not equate to the view being installed or not. From the Apple documentation on Installing and Uninstalling Views for a Size Class:

A runtime object for an uninstalled view is still created. However, the view and any related constraints are not added to the view hierarchy and the view has a superview property of nil. This is different from being hidden. A hidden view is in the view hierarchy along as are any related constraints.

So it sounds like the equivalent in code is something like:

//  "Uninstall" the view from the superview
[self.myView removeFromSuperView];

//  And add it back in
[self.view addSubview:self.myView]

You'd still have the view in memory, though not hidden. However you go about this I'm guessing your activating and deactivating constraints as this view comes and goes (unless the view itself is overlaying other things on the screen and not requiring a rearrangement of objects).

Upvotes: 2

Related Questions