What is the best way to remove all subviews from parent view/super view?


While working on project, sometime you encountered a situation where you need to remove all subviews from it superview. To achieve this, you need to follow steps below:

  1. Get all the subviews from its superview by calling subviews method.
  2. Iterator over the all subviews.
  3. Remove subview by calling removeFromSuperview method on it.

In Objective-C:

// Remove all subviews from self.view
    for (UIView *subUIView in self.view.subviews) {
        [subUIView removeFromSuperview];
    }

In Swift:

for subUIView in self.subviews as [UIView] {
    subUIView.removeFromSuperview()
}

Best way to remove all subviews:

If you want to remove all the subviews from its superview, then you can achieve same result as above by writing single line of code.

    [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

For UIView, you can safely use makeObjectsPerformSelector: because the subviews property will return a copy of the array of subviews.

Using makeObjectsPerformSelector method you can remove all the subviews but,  not subviews based on conditions. So If you want to remove some specific subviews then you must have to iterate over all the subviews. Then based on your condition remove those specific subviews.

Consider you want to remove all the UIButton from your superview then my code will look like this.

    for (UIView *subView in self.view.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) { // Condition
            [subView removeFromSuperview];
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s