How to remove specific subview?

iWizard picture iWizard · May 3, 2012 · Viewed 24.9k times · Source

I've added subview (ViewController) to my ViewController:

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
[self.subView addSubview:location.view];

How can I latter remove this subview?

I know that for removing all subviews is:

for (UIView *subview in [self.view subviews]) {

  [subview removeFromSuperview];

}

Answer

fzwo picture fzwo · May 3, 2012

Quick and dirty: Give your view a tag, so you can later identify it:

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
UIView *viewToAdd = location.view;
viewToAdd.tag = 17; //you can use any number you like
[self.view addSubview:viewToAdd];

Then, to remove:

UIView *viewToRemove = [self.view viewWithTag:17];
[viewToRemove removeFromSuperview];

A cleaner, faster, easier to read and to maintain alternative would be to create a variable or property to access the view:

In the interface:

@property (nonatomic, weak) UIView *locationView;

In the implementation:

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
UIView *viewToAdd = location.view;
self.locationView = viewToAdd;
[self.view addSubview:viewToAdd];

Then, to remove:

[self.locationView removeFromSuperview];

That said, heed the warnings from commenters about playing with other ViewControllers' Views. Read up on ViewController containment if you want to do it.