从子视图中移除所有UIButton

5

我正在编程地向我的视图中添加一些UIButtons。点击其中一个按钮后,它们所有的都应该被 'removeFromSuperView' 或释放,而不仅仅是一个。

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

我希望有人能够帮助我解决这个问题!

4个回答

8
更高效的方法是在创建每个按钮时将其添加到数组中,然后当按下一个按钮时,让数组中的所有按钮调用-removeFromSuperView方法,如下所示:
[arrayOfButtons makeObjectsPerformSelector:@selector(removeFromSuperView)];

接下来,您可以将按钮保留在数组中并重复使用,或者调用removeAllObjects释放它们。然后您可以稍后再次开始填充。

这样可以避免您必须遍历整个视图层次结构查找按钮。


真的是一个非常干净的想法。我总是这样做,使用额外的视图,然后对该视图执行“makeObjectsPerformSelector:”。但是使用数组来完成这个操作会更好。 - choise

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

2
NSMutableArray *buttonsToRemove = [NSMutableArray array];
for (UIView *subview in self.view.subviews) {
    if ([subview isKindOfClass:[UIButton class]]) {
        [buttonsToRemove addObject:subview];
    }
}
[buttonsToRemove makeObjectsPerformSelector:@selector(removeFromSuperview)];

编辑:
我已经编辑了我的答案,提供了更好的解决方案。
现在,在枚举数组时不会从中移除对象...


"for (UIView *subview in self.view.subviews)" 应该是这样。 - Felix Lamouroux
谢谢Michael!在将(UIView *subview in self.view)更改为:(UIView *subview in [self.view subviews])之后,它就像魔法般地运行了! - Martijn
@Felix,感谢您的纠正。您是完全正确的。我已经编辑了我的回答。 - Michael Kessler
我对这个答案进行了负评,因为它给出了错误的建议。苹果明确表示,在使用快速枚举时,您不应该修改集合的内容。请参见http://developer.apple.com/Mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocFastEnumeration.html#//apple_ref/doc/uid/TP30001163-CH18-SW1 - Stefan Arentz

1

还可以尝试这个,非常简单:

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

正如St3fan所说,使用快速枚举时,您不应修改集合的内容。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接