Iphone 移除所有UIButton';从子视图中删除

Iphone 移除所有UIButton';从子视图中删除,iphone,objective-c,uiview,uibutton,Iphone,Objective C,Uiview,Uibutton,我正在以编程方式向视图中添加几个UIButton。单击其中一个按钮后,它们都应该被“从SuperView中移除”或释放,而不仅仅是一个 for (int p=0; p<[array count]; p++) { button = [[UIButton alloc] initWithFrame:CGRectMake(100,100,44,44)]; button.tag = p; [button setBackgroundImage:[UIImage im

我正在以编程方式向视图中添加几个UIButton。单击其中一个按钮后,它们都应该被“从SuperView中移除”或释放,而不仅仅是一个

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];  
}
-(void) action:(id)sender{  
    UIButton *button = (UIButton *)sender;  
    int pressed = button.tag;  
    [button removeFromSuperview];  
}
我希望有人能帮我做这个

NSMutableArray *buttonsToRemove = [NSMutableArray array];
for (UIView *subview in self.view.subviews) {
    if ([subview isKindOfClass:[UIButton class]]) {
        [buttonsToRemove addObject:subview];
    }
}
[buttonsToRemove makeObjectsPerformSelector:@selector(removeFromSuperview)];
编辑
我已将我的答案编辑为更好的解决方案。

现在,枚举数组时不会从数组中删除对象…

更有效的方法是在创建数组时将每个按钮添加到数组中,然后在按下按钮时,让数组中的所有按钮调用
-removeFromSuperView
方法,如下所示:

[arrayOfButtons makeObjectsPerformSelector:@selector(removeFromSuperView)];
然后,您可以将按钮保留在数组中并重用它们,或者调用
removeAllObjects
释放它们。然后,您可以稍后再次开始填充它


这使您不必在整个视图层次结构中寻找按钮。

另一个答案仅供参考:

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];
    }
}

也可以试试这个,非常简单:

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

应该是“for(UIView*self.view.subview中的子视图)”我猜是nx Micheal!在:(UIView*子视图在[self.view子视图]中)更改(UIView*子视图在self.view子视图中)后,它就像一个符咒一样工作@菲利克斯,谢谢你的更正。你完全正确。我编辑了我的答案。我否决了这个答案,因为这是一个糟糕的建议。Apple明确指出,在使用快速枚举时,不应修改集合的内容。看真干净的主意。我总是这样做,使用一个额外的视图,然后对该视图执行“makeObjectsPerformSelector:”。但使用数组进行此操作要好得多。正如St3fan所说,在使用快速枚举时,不应修改集合的内容。