Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove all UIButton's from subview

i'm programmatically adding a couple UIButtons to my view. After clicking one of the buttons they all should be 'removeFromSuperView' or released, not just one.

for (int p=0; p<[array count]; p++) {  
    button = [[UIButton alloc] initWithFrame:CGRectMake(100,100,44,44)];  
    button.tag = p;  
    [button setBackgroundImage:[UIImage imageNamed:@"image.png"]   forState:UIControlStateNormal];    
    [self.view addSubview:button];    
    [button addTarget:self action:@selector(action:)   forControlEvents:UIControlEventTouchUpInside];  
}

Now this is the part where all buttons should be removed. Not just one.

-(void) action:(id)sender{  
    UIButton *button = (UIButton *)sender;  
    int pressed = button.tag;  
    [button removeFromSuperview];  
}

I hope someone can help me with this one!

like image 714
Martijn Avatar asked Feb 03 '10 10:02

Martijn


People also ask

How remove all Subviews from Stackview?

Managing Subviews To remove an arranged subview that you no longer want around, you need to call removeFromSuperview() on it. The stack view will automatically remove it from the arranged subview list.


2 Answers

A more efficient way would be to add each button to an array when you create it, and then when a button is pressed, have all the buttons in the array call the -removeFromSuperView method like this:

[arrayOfButtons makeObjectsPerformSelector:@selector(removeFromSuperView)];

Then after that, you can either keep the buttons in the array and reuse them, or call removeAllObjects to have them released. Then you can start populating it again later.

This saves you from having to walk through the entire view hierarchy looking for buttons.

like image 153
Jasarien Avatar answered Sep 28 '22 12:09

Jasarien


Another answer just for reference:

for (int i = [self.view.subviews count] -1; i>=0; i--) {
    if ([[self.view.subviews objectAtIndex:i] isKindOfClass:[UIButton class]]) {
        [[self.view.subviews objectAtIndex:i] removeFromSuperview];
    }
}
like image 38
Daniel Avatar answered Sep 28 '22 12:09

Daniel