Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to remove a subview from a view hierarchy and nuke it?

I have a parent UIView with a number of subviews. Periodically I need to remove a subview and completely remove it from the system. What is the correct way to do this? I tried this:

UIView *v = [self.containerView viewWithTag:[n integerValue]];  [v removeFromSuperview]; 

and got a bizarre result. Previously present UIViews disappeared as well. What's going on?

like image 234
dugla Avatar asked Oct 04 '09 12:10

dugla


People also ask

How do I delete all Subviews?

[someNSView setSubviews:[NSArray array]]; For UIView (iOS development only), you can safely use makeObjectsPerformSelector: because the subviews property will return a copy of the array of subviews: [[someUIView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

How do you delete a view in Swift?

If you add a tag to your view you can remove a specific view.


2 Answers

Try this:

UIView *v = [self.containerView viewWithTag:[n integerValue]]; v.hidden = YES; [self.containerView bringSubviewToFront:v]; [v removeFromSuperview]; 

Another thing I just noticed from the UIView class document - see the last sentence:

removeFromSuperview Unlinks the receiver from its superview and its window, and removes it from the responder chain.

  • (void)removeFromSuperview

Discussion If the receiver’s superview is not nil, this method releases the receiver. If you plan to reuse the view, be sure to retain it before calling this method and be sure to release it as appropriate when you are done with it or after adding it to another view hierarchy.

Never invoke this method while displaying.

UPDATE: It is now 2014 and removing a subview without hiding it works perfectly fine. The original poster's code should work as-is:

UIView *v = [self.containerView viewWithTag:[n integerValue]]; [v removeFromSuperview]; 

This will remove v and any views it has attached to it as subviews, leaving behind containerView and any siblings of v.

like image 70
mahboudz Avatar answered Oct 13 '22 06:10

mahboudz


To remove all subviews from your view:

for(UIView *subview in [view subviews]) {    [subview removeFromSuperview]; } 

If you want to remove some specific view only then:

for(UIView *subview in [view subviews]) {   if([subview isKindOfClass:[UIButton class]]) {      [subview removeFromSuperview];  } else {      // Do nothing - not a UIButton or subclass instance  } } 

You can also delete sub views by tag value:

for(UIView *subview in [view subviews]) {     if(subview.tag==/*your subview tag value here*/) {         [subview removeFromSuperview];      } else {         // Do nothing - not a UIButton or subclass instance     } } 
like image 36
iKushal Avatar answered Oct 13 '22 05:10

iKushal