如何将所有以编程方式添加的ImageViews设置为nil?

时间:2014-01-05 20:53:47

标签: iphone cocoa-touch uiimageview

每次单击“创建”按钮时,都会创建4行图像。我正在将这种技术用于游戏策划者。当您单击清除按钮时,每个imageview必须设置为nil,但现在只有最后创建的4个imageview设置为nil。任何帮助将不胜感激!

- (IBAction)create {

    _imgView1 = [[UIImageView alloc] initWithFrame:CGRectMake(134, y, 30, 30)];
    _imgView2 = [[UIImageView alloc] initWithFrame:CGRectMake(170, y, 30, 30)];
    _imgView3 = [[UIImageView alloc] initWithFrame:CGRectMake(206, y, 30, 30)];
    _imgView4 = [[UIImageView alloc] initWithFrame:CGRectMake(241, y, 30, 30)];

    _imgView1.image = [UIImage imageNamed:[textfield_code objectAtIndex:0]];
    _imgView2.image = [UIImage imageNamed:[textfield_code objectAtIndex:1]];
    _imgView3.image = [UIImage imageNamed:[textfield_code objectAtIndex:2]];
    _imgView4.image = [UIImage imageNamed:[textfield_code objectAtIndex:3]];

    [self.view addSubview:_imgView1];
    [self.view addSubview:_imgView2];
    [self.view addSubview:_imgView3];
    [self.view addSubview:_imgView4];


    y += 41;
}

- (IBAction)clear {
    [_imgView1 setImage:nil];
    [_imgView2 setImage:nil];
    [_imgView3 setImage:nil];
    [_imgView4 setImage:nil];
}

1 个答案:

答案 0 :(得分:0)

枚举视图的子视图

for(UIImageView *v in self.view.subviews) {
    if([v isKindOfClass:[UIImageView class]) {
       [v setImage:nil];
    }
}

但这是'危险',因为它删除了任何图像视图。 最好使用标签

e.g。

将其定义为#define MyTag 100

何时会创建v.tag = MyTag

然后在循环中检查if(v.tag == MyTag)