Search code examples
objective-ccocoa-touchuiviewuiimageviewuitouch

Xcode remove touch event images?


I'm using this code to display random images on the screen.

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    UIImageView *cloud = [[UIImageView alloc] 
                               initWithImage:[UIImage imageNamed:@"spit.png"]];

    cloud.center = CGPointMake(random() % 250, random() % 400); //Random place
    [cloud setAlpha:1];
    [self.view addSubview:cloud];
    [cloud release];

    cloud.frame = CGRectMake(0, 0, 300, 300); 

    [UIView beginAnimations: @"cloddy" context: nil];
    [UIView setAnimationDuration: 0.5f];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseIn];

    // Size when done
    cloud.frame = CGRectMake(0, 0, 75, 75); 
    cloud.center = location;
    [UIView commitAnimations]; 
}

after a couple of touches the screen gets kinda full. How do I remove them inside another IBAction? And why does the animation always start in the upper left corner even though I'm using random?


Solution

  • Assuming that the only subviews that have been added to your view are clouds,

    - (IBAction)clearClouds:(id)sender{
        [[[self view] subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)];
    }
    

    The cloud is always starting at the upper left because this line: cloud.frame = CGRectMake(0, 0, 300, 300);resets its origin to 0,0. Move cloud.center = CGPointMake(random() % 250, random() % 400); below the line where you set the cloud's frame and you should be all set.