-2

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

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

所以添加它们:(在 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];
    }
4

5 回答 5

2

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

我没有链接到他们

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

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

- (void)removeUIButtonsFromView:(UIView *v)
{
    for (UIView *sub in v.subviews) {
        if ([sub isKindOfClass:[UIButton class]]) {
            [sub removeFromSuperview];
        } else {
            [self removeUIButtonsFromView:sub];
        }
    }
}
于 2013-02-27T15:46:00.630 回答
1
for (UIView *subview in [((UIView *)sview).subviews copy]) {
    if ([subview isKindOfClass:[UIButton class]])
        [subview removeFromSuperview];
}
于 2013-02-27T15:45:39.250 回答
1

如果它只是滚动视图中的按钮,请使用以下命令将它们全部删除:

[sview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
于 2013-02-27T15:47:18.457 回答
1

有几种方法可以做到。有人提出了一种方法。我个人喜欢将我添加的所有内容保存在一个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我不必担心。

于 2013-02-27T15:52:34.440 回答
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;
}
于 2013-02-27T15:48:27.943 回答