在运行时将图像添加到数组并在按钮单击时清除它

时间:2010-07-08 04:46:31

标签: iphone cocoa-touch

我想尝试的是,每当用户触摸屏幕时,我在屏幕上添加一个小的bulletr图像

UIImage *img = [UIImage imageNamed:@"shoot_a.png"]; //bullet shot image
        im.image = img;
[self.view addSubview:im];

,如果用户触摸50次,屏幕上将会有50张图像。

现在我想,如果用户按下按钮,则应从屏幕上删除所有这些子弹。

我希望我清楚自己的问题。

[im removefromsuperview]对我不起作用。

如果我想在运行时向阵列添加图像,我该如何添加和发布? 还是有更好的方法来清除所有图像 问候。


这是我的触摸方法,我在屏幕上添加了子弹图像,但这些图像没有添加到数组中

// Touch method
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if(restrictTap == YES){



    NSUInteger numTaps = [[touches anyObject] tapCount];
    NSString *numTapsMessage = [[NSString alloc] initWithFormat:@"%i", numTaps];
        [numTapsMessage release];
    // getting location
    CGPoint touchLocation = [[touches anyObject] locationInView:self.view];
    NSString *locationMessage = [[NSString alloc] initWithFormat:@"Location: X = %.0f Y = %.0f", touchLocation.x, touchLocation.y];
        //bullet shot  image
        im = [[UIImageView alloc] initWithFrame:CGRectMake(self.location.x, self.location.y, 12.0, 12.0)];

        float j =self.location.x;
        float i =self.location.y;

        img = [UIImage imageNamed:@"shoot_a.png"]; //bullet shot image
        im.image = img;
         //im.hidden = NO;
        [self.view addSubview:im]; ///bullet shot image is over transparent view            

        [imageArray addObject:img];



}
}

2 个答案:

答案 0 :(得分:1)

您可以通过NSMutableArray属性跟踪它们并使用它来删除它们:

// create e.g. in initializer:
imageArray = [[NSMutableArray alloc] init];

// clean-up, e.g. in dealloc:
self.imageArray = nil;

// add image:
[imageArray addObject:im];

// remove all:
for (UIView *img in imageArray) {
    [img removeFromSuperview];
}
[imageArray removeAllObjects];

答案 1 :(得分:1)

将视频添加到视图中时,可以将特定标记设置为所有项目符号图像

im.tag = 1000;

然后在按钮触摸上,您可以遍历视图的子视图数组并删除具有该标记的所有视图。类似的东西:

    int count = [[self.view subviews] count];

for(int i = 0; i < count; i++)
{
    if([(UIView*)[[self.view subviews] objectAtIndex:i] tag] == 1000)
    {
        [(UIView*)[[self.view subviews] objectAtIndex:i] removeFromSuperview]
    }
}