从视图中删除所有UIButtons?

时间:2013-02-27 15:41:53

标签: ios objective-c cocos2d-iphone

我很难从视图中删除所有UIButtons。

我已在for循环中将它们添加到UIScrollView,稍后我需要删除它们。

所以添加它们:(通过cocos2d场景)

sview = [[UIScrollView alloc]
                          initWithFrame:[[UIScreen mainScreen] bounds]];

......
for(int i =0; i<[assets count]-1; i++)  
    {

        UIImage *thumb= [assets objectAtIndex:i];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
               [sview addSubview:button];
.......
 [[[CCDirector sharedDirector] view] addSubview:sview];

并删除它们:

[((UIView *)sview) removeFromSuperview]; //which usually works but no now .

我如何在以后运行所有这些按钮并删除它们? 我没有链接到他们,我想在视图中的所有按钮上运行..

编辑:已成功尝试

for (int i=0; i<[assets count];i++)
    {
        UIButton *myButton = (UIButton *)[sview viewWithTag:i];
         [((UIView *)myButton) removeFromSuperview];
    }

5 个答案:

答案 0 :(得分:2)

虽然技术上可行,但设计这样的代码并不是一个好主意。

  

我没有链接到他们

这就是你的问题所在。在创建和添加它们时将它们放在NSMutableArray中,然后遍历此数组以删除它们。

但是,如果由于某种原因,您不能这样做,您可以检查您的视图的所有子视图是否为UIButton:

- (void)removeUIButtonsFromView:(UIView *v)
{
    for (UIView *sub in v.subviews) {
        if ([sub isKindOfClass:[UIButton class]]) {
            [sub removeFromSuperview];
        } else {
            [self removeUIButtonsFromView:sub];
        }
    }
}

答案 1 :(得分:1)

for (UIView *subview in [((UIView *)sview).subviews copy]) {
    if ([subview isKindOfClass:[UIButton class]])
        [subview removeFromSuperview];
}

答案 2 :(得分:1)

如果它只是滚动视图中的按钮,请将它们全部删除:

[sview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

答案 3 :(得分:0)

[((UIView *)sview) removeFromSuperview]

您要删除滚动视图sview:为什么?

添加按钮时,只需将它们添加到您保留的NSArray属性中即可。 然后只要想要删除它们就迭代该数组

//in your interface

@property (nonatomic, strong) NSArray *buttons;

//in your implementation

sview = [[UIScrollView alloc]
                          initWithFrame:[[UIScreen mainScreen] bounds]];

......
NSMutableArray *tempArray = [NSMutableArray array];
for(int i =0; i<[assets count]-1; i++)  
    {

        UIImage *thumb= [assets objectAtIndex:i];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
               [sview addSubview:button];
        [tempArray addObject:button];
    }
    self.buttons = tempArray;
.......

// later, to remove all buttons

- (void) removeButtons
{
    for(UiButton *button in self.buttons){
        [button removeFromSuperview];
    }
    self.buttons = nil;
}

答案 4 :(得分:0)

有几种方法可以做。有些人提出了一种方法。我个人喜欢将我添加的所有内容保存在NSMutableArray中(当您将它们添加到视图中时添加到数组中),然后循环遍历数组以删除它们。

for ( ... ; ... ; ...) {
    UIButton *button = ....
    // in your "add button loop" just record them in an array
    [self.transientViews addObject:button];
}


// remove them later with
for (UIView *view in self.transientViews)
    [view removeFromSuperview];
[self.transientViews removeAllObjects];

我喜欢这个,因为它给了我更大的灵活性。我可能想删除它们或其他东西。它们可以是UIView的任何子类,我不必担心它。