开发者

Cocoa Touch - Touches In a UIImageView

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"];
开发者_StackOverflow中文版
    [self.view addSubview: starImgView]; 

    [starImgView release];
}


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜