How to remove subviews in Objective-C?

mac picture mac · Jun 9, 2010 · Viewed 53.9k times · Source

I have added UIButton and UITextView as subviews to my view programmatically.

notesDescriptionView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,460)];
notesDescriptionView.backgroundColor = [UIColor redColor];
[self.view addSubview:notesDescriptionView];

textView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,320,420)]; 
[self.view addSubview:textView]; 
printf("\n description  button \n");

button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button
  addTarget:self action:@selector(cancel:)
  forControlEvents:UIControlEventTouchDown];
[button setTitle:@"OK" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 420.0, 160.0, 40.0);
[self.view addSubview:button];

I need to remove all subviews when the button is clicked.

I have tried:

[self.view removeFromSuperView]

but it's not working.

Answer

mac picture mac · Jun 9, 2010

to remove all the subviews you added to the view

use the following code

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