Reputation: 21
In XCode 5, how could I have it so that when I tap a UIImage something will happen. Like a button but I dont want to use a button. I need it to be an image. I am making a game and I couldn't find how to do this anywhere else so please help.
Upvotes: 0
Views: 1545
Reputation: 14030
In order to display your UIImage
, it needs to be attached to a UIView
or CALayer
. You could do this:
UIImageView *notAButton = [[UIImageView alloc] initWithImage:myImage];
[notAButton setUserInteractionEnabled:YES];
[notAButton addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedButton:)]];
[self.view addSubview notAButton];
What do you have against UIButton
, by the way? It is by far the easiest and most widely-accepted way to do this.
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setImage:myImage forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(tappedButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:aButton];
Upvotes: 2
Reputation: 535801
There's no such thing as a loose image, so the image must be inside something that displays it. Make sure that that something (it might be an image view) has its user interaction enabled. Then attach a UITapGestureRecognizer to it.
Upvotes: 2