views:

141

answers:

1

How can I make it so the image goes away when it is touched.

Here is my code to create the image. It is randomly displayed on screen so after you touch it, it disappears and a new image in a new place appears.

-(void)drawStarsAndDetectTouches{ //uses random numbers to display a star on screen
    //create random position
    int xCoordinate = arc4random() % 267;
    int yCoordinate = arc4random() % 420;

    //make sure it doesnt draw onto titiles
    if (yCoordinate <= 40) {
        yCoordinate = arc4random() % 420;
    }

    UIImageView *starImgView = [[UIImageView alloc] initWithFrame:CGRectMake(xCoordinate, yCoordinate, 58, 40)]; //create ImageView 
    starImgView.image = [UIImage imageNamed:@"star.png"];

    [self.view addSubview: starImgView]; 

    [starImgView release];
}
A: 

From the top of my head, I can think of two ways you can achieve this.

Either work with a UIButton instead of a UIImageView. Set the button's type to "custom" in Interface Builder and choose your image as the background image of the button. Assign an IBAction to the button and make it invisible from your action.

If - for whatever reason - you have to stick with an UIImageView, create a subclass that overrides -touchesBegan:inView:. Additionally, make sure that you set the image view's userInteractionEnabled property to YES so that your -touchesBegan:inView: selector is called whenever the user touches the view. The default value of that property for UIImageView is NO so the last step is important!

Update Here's some sample code to get you started with the button approach in case you need to do this programmatically:

UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:img forState:UIControlStateNormal];
[btn addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn];
Benjamin
If i want to use a custom button (seems easier) can I edit my code above to be a button? since it needs to be done all programically
Yep, that should work. I think you can do something like what I just edited into my answer.
Benjamin