Remove all UIButton from subview

I programmatically add a couple of UIButtons to my view. After clicking one of the buttons, they should all be "removeFromSuperView" or released, and 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 the buttons should be removed. Not alone.

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

I hope someone can help me with this!

+5
source share
4 answers

A more efficient way would be to add each button to the array when it is created, and then when the button is pressed, all the buttons in the array will call the method -removeFromSuperViewas follows:

[arrayOfButtons makeObjectsPerformSelector:@selector(removeFromSuperView)];

, , removeAllObjects, . .

, .

+8

:

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];
    }
}
+8
NSMutableArray *buttonsToRemove = [NSMutableArray array];
for (UIView *subview in self.view.subviews) {
    if ([subview isKindOfClass:[UIButton class]]) {
        [buttonsToRemove addObject:subview];
    }
}
[buttonsToRemove makeObjectsPerformSelector:@selector(removeFromSuperview)];

:
.
...

+2

:

 for (UIButton *btn in self.view.subviews){     
              [btn removeFromSuperview]; //remove buttons
    }
+2

All Articles