How to remove all views inside another view – iOS, iPhone, iPad

Let’s say we have a UIScrollView (myScrollView) in our application view. Inside UIScrollView we have couple of different subclasses of UIView (UILabel, UISegmentedControl, UIButton), like shown on the picture below.

Every subclass of UIView has a method subviews, which returns NSArray of all the views that are nested inside the view. Since UIScrollView is the subclass of UIView, we can do the following, for example inside viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
	UISeg
	for (UIView *aView in [myScrollView subviews]){
		NSLog(@"Class: %@", [aView class]);
	}
}
//Returnes 
//Class: UISegmentedControl
//Class: UILabel
//Class: UILabel
//Class: UILabel
//Class: UIRoundedRectButton
//Class: UITextField
//Class: UIImageView
//Class: UIImageView

Now if we wanted to delete all the subviews inside UIScrollView we would do

[aView removeFromSuperview];

and thus our UIScrollView would now be empty.

If we wanted to remove just UILabels from our UIScrollView we would do:

if ([aView isKindOfClass:[UILabel class]]){
			[aView removeFromSuperview];
		}
Advertisements

, , , ,

  1. #1 by Bishal Ghimireishal on July 16, 2012 - 2:47 am

    How about if the have added the image view dynamically
    and we need to remove only selected one once at a time ( remove them in some random order )

    image = [UIImage imageNamed:@”yellowDot.png”];
    image.size.width, image.size.height);
    rect = CGRectMake(flagGrid[touchCount][1]-10, flagGrid[touchCount][2]-10, 25, 25);

    imageView = [[UIImageView alloc] initWithFrame:rect];
    [imageView setImage:image];
    [self.view addSubview:imageView];

    • #2 by Ladislav Klinc on July 16, 2012 - 7:49 pm

      After you added the view, you can still remove it, since you added it to the self.view, when you get NSArray with all the views ([self.view subviews]), your new view will be one of the view’s returned.

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

%d bloggers like this: